Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在值中排序基于HashMap的整数数组_Java_Hashmap - Fatal编程技术网

Java 在值中排序基于HashMap的整数数组

Java 在值中排序基于HashMap的整数数组,java,hashmap,Java,Hashmap,我想根据整数数组中的第二个元素对HashMap进行排序 例子:考虑我有一个像下图的哈希图。 <"Alex",[12,18]> <"Bob",[13,45]> <"Ball",[13,45]> <"Candy",[1,2]> 我们可以使用Lambda函数吗?假设1:int数组已经排序 在Java中使用Lambda的 HashMap<String, int[]> map = new HashMap<>();

我想根据整数数组中的第二个元素对HashMap进行排序

例子:考虑我有一个像下图

的哈希图。
<"Alex",[12,18]> 

<"Bob",[13,45]>

<"Ball",[13,45]>

<"Candy",[1,2]>

我们可以使用Lambda函数吗?

假设1:int数组已经排序

在Java中使用Lambda的

HashMap<String, int[]> map = new HashMap<>();

    map.put("Alex", new int[] {12,18});
    map.put("Bob", new int[] {13,45});
    map.put("Ball", new int[] {13,45});
    map.put("Candy", new int[] {1,2});

    Map<String, int[]> result = map.entrySet().stream()
            .sorted(Map.Entry.comparingByValue((int[] a, int[] b) ->
                    IntStream.of(b).sum() - IntStream.of(a).sum())
            )
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    System.out.println(result);
HashMap map=newhashmap();
map.put(“Alex”,新int[]{12,18});
map.put(“Bob”,新int[]{13,45});
map.put(“Ball”,新int[]{13,45});
map.put(“Candy”,新int[]{1,2});
Map result=Map.entrySet().stream()
.sorted(Map.Entry.comparingByValue((int[]a,int[]b)->
IntStream.of(b.sum()-IntStream.of(a.sum())
)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,
(oldValue,newValue)->oldValue,LinkedHashMap::new));
系统输出打印项次(结果);
Groovy中的奖金:

HashMap<String, List> map = new HashMap<String, List>()

map.put("Alex", [12,18])
map.put("Bob", [13,45])
map.put("Ball", [13,45])
map.put("Candy", [1,2])

println map.sort {a,b -> b.value.sum() <=> a.value.sum()}
HashMap=newhashmap()
地图放置(“Alex”[12,18])
地图放置(“鲍勃”,[13,45])
图.推杆(“球”[13,45])
地图放置(“糖果”[1,2])
println map.sort{a,b->b.value.sum()a.value.sum()}

您可以将HashMap键放入列表中,并让排序的比较函数从相应的HashMap条目中查找所需的比较值。
HashMap
无法排序,因为它是一个顺序不保证的关联容器。此外,您尝试按值(而不是按键)排序,这通常是
Map
所不期望的。以一种简单的方式完成此操作的唯一方法是收集
Map.Entry
元素作为列表并对列表进行排序。
HashMap<String, List> map = new HashMap<String, List>()

map.put("Alex", [12,18])
map.put("Bob", [13,45])
map.put("Ball", [13,45])
map.put("Candy", [1,2])

println map.sort {a,b -> b.value.sum() <=> a.value.sum()}