java对对象进行分组统计

原来需要:

Map<String, List<Employee>> result = new HashMap<>();
for (Employee e : employees) {
  String city = e.getCity();
  List<Employee> empsInCity = result.get(city);
  if (empsInCity == null) {
    empsInCity = new ArrayList<>();
    result.put(city, empsInCity);
  }
  empsInCity.add(e);
}

简化后(用stream):

Map<String, List<Employee>> employeesByCity =
  employees.stream().collect(groupingBy(Employee::getCity));

参考:https://www.jianshu.com/p/f5655ca08c0f
原文链接: javacodegeeks 翻译: ImportNew.com - paddx
译文链接: http://www.importnew.com/17313.html
[ 转载请保留原文出处、译者和译文链接。]

同时可参考:JAVA8用stream解决分组的问题

你可能感兴趣的:(java问题总结)