首页 > 解决方案 > Java 8:从列表中将元素收集为 TreeMap 的有效方法

问题描述

我有一个Student对象如下

class Student{
    String name,email,country;
    //getters setters
}

我需要收集元素,TreeMap<String,List<String>>其中 key 是学生的country,value 是列表email

Map<String, List<Student>> countryStudents = students.stream()
            .collect(Collectors.groupingBy(Student::getCountry));
Map<String,List<String>> map = new HashMap<>();
        countryStudents .entrySet().forEach(entry -> map.put(entry.getKey(),entry.getValue().stream().map(student -> student .getEmail()).collect(Collectors.toList())));

我想知道是否有任何有效的方法可以做到这一点,而不是在 2 次迭代中做到这一点。

标签: javaoptimizationjava-8

解决方案


您可以将groupingBy收集器与mapping收集器一起使用,一次性完成。这是它的外观。

Map<String, List<String>> map = students.stream()
    .collect(Collectors.groupingBy(Student::getCountry, TreeMap::new, 
        Collectors.mapping(Student::getEmail, Collectors.toList())));

或者,一种更好的方法是使用computeIfAbsent在列表中单遍构建地图。如果我是你,我宁愿用这个。

Map<String, List<String>> stdMap = new TreeMap<>();
for (Student student : students) 
    stdMap.computeIfAbsent(student.getCountry(), unused -> new ArrayList<>())
        .add(student.getEmail());

推荐阅读