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

PAA*_*PAA 3 java java-8 java-stream

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

RESULT : {papaya=1, orange=1, banana=2, apple=3}
FINAL RESULT : {apple=3, banana=2, papaya=1, orange=1}
Run Code Online (Sandbox Code Playgroud)

我想要如下的输出

RESULT : {apple=3,banana=2, orange=1,papaya=1}
Run Code Online (Sandbox Code Playgroud)

Fed*_*ner 5

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

LinkedHashMap版本:

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

TreeMap版本:

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

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

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

它使用Map.merge方法并且更短且性能更高。

  • 我也更喜欢“TreeMap”版本,因为它不需要预先对整个数据集进行排序。然而,非流版本的性能差异可能可以忽略不计。 (2认同)