繁体   English   中英

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

[英]Java 8 - Group by a List, sort and display the total count of it

我只是在使用streamJava8使用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}

您只需要使用Supplier<Map>使用此版本的重载方法groupingBy为您创建LinkedHashMap

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}

您可以对流进行排序,然后将条目添加到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方法,并且更短,性能更高。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM