gpt4 book ai didi

Java 8 - 按列表分组,排序并显示它的总数

转载 作者:行者123 更新时间:2023-12-03 23:11:28 30 4
gpt4 key购买 nike

我只是在使用 streams 来玩 Java8 中的 groupingBy。我无法根据水果的名称对水果进行排序,我还想根据水果的名称对 (//1.1== >按列表分组并显示其总数)

public class StreamCollectorsGroupingByDemo {
public static void main(String[] args) {
List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya");

// 1.1== >Group by a List and display the total count of it
Map<String, Long> result = items.stream()
.sorted()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("RESULT : "+result);

// 1.2 Add sorting
Map<String, Long> finalMap = new LinkedHashMap<>();
result.entrySet().stream()
.sorted(Map.Entry.<String, Long> comparingByValue()
.reversed())
.forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));
System.out.println("FINAL RESULT : "+finalMap);
}
}

输出为:

RESULT : {papaya=1, orange=1, banana=2, apple=3}
FINAL RESULT : {apple=3, banana=2, papaya=1, orange=1}

我想要下面的输出

RESULT : {apple=3,banana=2, orange=1,papaya=1}

最佳答案

您可以对流进行排序,然后将条目添加到 LinkedHashMap,或者根本不对流进行排序并将条目添加到 TreeMap,以便排序插入树时完成。

LinkedHashMap 版本:

Map<String, Long> result = items.stream()
.sorted()
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()));

TreeMap 版本:

Map<String, Long> result = items.stream()
.collect(Collectors.groupingBy(
Function.identity(),
TreeMap::new,
Collectors.counting()));

您可能还想使用非流版本:

Map<String, Long> result = new TreeMap<>();
items.forEach(e -> result.merge(e, 1L, Long::sum));

其中使用 Map.merge方法,并且更短且性能更高。

关于Java 8 - 按列表分组,排序并显示它的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47019946/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com