streamCollectGroupingBySort

public class StreamGroupingByCountingDemo {
    public static void main(String[] args) {
        List<String> items =
                Arrays.asList("apple", "pear", "apple", "banana", "blueberry", "pear",
                        "apple", "orange", "banana", "papaya", "blueberry", "pear");
        Map<String, Long> result =
                items.stream().collect(
                        Collectors.groupingBy(Function.identity(), Collectors.counting())
                );
        System.out.println(result);
    }
}
{papaya=1, orange=1, banana=2, apple=3, pear=3, blueberry=2}

+ LinkedHashMap::new

public class StreamGroupingByCountingDemo {
    public static void main(String[] args) {
        //3 apple, 2 banana, others 1
        List<String> items =
                Arrays.asList("apple", "pear", "apple", "banana", "blueberry", "pear",
                        "apple", "orange", "banana", "papaya", "blueberry", "pear");
        Map<String, Long> result =
                items.stream().collect(
                        Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())
                );
        System.out.println(result);
    }
}
{apple=3, pear=3, banana=2, blueberry=2, orange=1, papaya=1}

doc:


doc

推荐阅读更多精彩内容