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

时间:2017-10-30 16:22:51

标签: java java-8 java-stream

我正在使用溪流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}

2 个答案:

答案 0 :(得分:3)

您只需使用Supplier<Map>即可使用this version重载方法LinkedHashMap为您创建groupingBy

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

现在输出是:

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

答案 1 :(得分:3)

您可以对流进行排序,然后将条目添加到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));

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

{{1}}

使用Map.merge方法并且更短且更高效。