Java8-按列表分组,排序并显示其总数
我只是在Java8-按列表分组,排序并显示其总数,java,java-8,java-stream,Java,Java 8,Java Stream,我只是在Java8中使用streams玩groupby。我无法根据水果的名称对水果进行排序,我还想根据(//1.1==>按列表分组并显示其总数)的水果名称进行排序 我希望输出如下 RESULT : {apple=3,banana=2, orange=1,papaya=1} 您只需使用Supplier,它将使用重载方法groupingBy为您创建LinkedHashMap: Map<String, Long> result = items.stream() .sort
Java8
中使用streams玩groupby。我无法根据水果的名称对水果进行排序,我还想根据(//1.1==>按列表分组并显示其总数)的水果名称进行排序
我希望输出如下
RESULT : {apple=3,banana=2, orange=1,papaya=1}
您只需使用
Supplier
,它将使用重载方法groupingBy
为您创建LinkedHashMap
:
Map<String, Long> result = items.stream()
.sorted()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
System.out.println("RESULT : "+result);
您可以对流进行排序,然后将条目添加到
LinkedHashMap
,或者根本不对流进行排序,然后将条目添加到TreeMap
,这样在插入到树时就可以完成排序
LinkedHashMap
版本:
Map<String, Long> result = items.stream()
.sorted()
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()));
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 result=newtreemap();
items.forEach(e->result.merge(e,1L,Long::sum));
它使用了方法,而且更短,性能更好。您要求在那里提供
映射,因此您的排序实际上毫无意义……从您当前的输出中,我已经看到结果是正确的,按顺序进行模化,最终结果实际上已经给出了您想要的顺序。我不确定是什么阻止您将最终结果转换为结果。您使用的是comparingByValue().reversed()
而不是comparingByValue()
,因此您的最终结果实际上是计数的相反顺序。我也更喜欢TreeMap
版本,因为它不需要预先对整个数据集进行排序。然而,非流版本的性能差异可能可以忽略不计。
Map<String, Long> result = items.stream()
.sorted()
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()));
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));