1. 传统方法: 新建HashMap然后for循环List去统计每个元素出现的次数的方法实现。
public static MapfrequencyOfListElements( List items ) { if (items == null || items.size() == 0) return null; Map map = new HashMap (); 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 list = new ArrayList() {{
add("test");
add("1");
add("1");
add("2");
add("3");
}};
//java8 优雅的stream
Map resMap = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(resMap);
}



