Java利用Stream统计List中每个元素的个数

1. 传统HashMap

新建HashMap然后for循环List去统计每个元素出现的次数的方法实现。

public static Map<String,Integer> frequencyOfListElements( List items ) {
        if (items == null || items.size() == 0) return null;
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (String temp : items) {
                Integer count = map.get(temp);
                map.put(temp, (count == null) ? 1 : count + 1);
        }
        return map;
}

2. 利用Stream

public static void main(String[] args) {
        //初始化list
        List<String> list = new ArrayList<String>() {
         
  {
            add("test");
            add("1");
            add("1");
            add("2");
            add("3");
        }};
        //java8 优雅的stream 
        Map<String, Long> resMap = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(resMap);
    }
经验分享 程序员 微信小程序 职场和发展