java - 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 次迭代中做到这一点。
解决方案
您可以将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());
推荐阅读
- slurm - 检索作业提交限制
- javascript - 如何突出显示表格列?
- php - 提交到下拉列表并显示所选值后如何保留ajax数据?
- python - Pandas 在第三个分隔符实例后拆分列?
- ios - Firebase Crashlytics for Swift 上未显示的实际原因
- linux - 如何通过特定的网络接口发送?
- kubernetes - 在 POD 中使用 Service 的 ClusterIP 地址
- ruby - 在 Ruby 块中运行 Execute 资源
- bazel - Bazel 选择在 ctx.file 中失败
- c - 为什么在命令行参数的情况下将命令 char 双指针转换为 char 不起作用?