【问题标题】:Java 8: Efficient way to Collect elements as TreeMap from List [duplicate]Java 8:从列表中将元素收集为 TreeMap 的有效方法 [重复]
【发布时间】:2020-10-10 12:10:43
【问题描述】:

我有一个Student 对象,如下所示

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

我需要将元素收集为TreeMap<String,List<String>>,其中键是学生的country,值是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 次迭代中完成。

【问题讨论】:

    标签: java optimization java-8


    【解决方案1】:

    您可以使用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());
    

    【讨论】:

    • 我觉得unused -&gt; new ArrayList&lt;&gt;()可以写成ArrayList::new
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多