英文:
Java 8: Efficient way to Collect elements as TreeMap from List
问题
我有一个以下的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())));
想知道是否有更高效的方法来完成这个任务,而不是分两次迭代。
英文:
I have a Student
object as below
class Student{
String name,email,country;
//getters setters
}
And I need collect the elements as TreeMap<String,List<String>>
where key is student's country
and value is the list of 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())));
Am wondering if is there any efficient way to do this instead of doing it in 2 iterations.
答案1
得分: 3
你可以使用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());
英文:
You can use groupingBy
collector along with mapping
collector to do it in one pass. Here's how it looks.
Map<String, List<String>> map = students.stream()
.collect(Collectors.groupingBy(Student::getCountry, TreeMap::new,
Collectors.mapping(Student::getEmail, Collectors.toList())));
Alternatively, a much better approach is to use computeIfAbsent
to construct the map in single pass over the list. If I were you, I would rather use this.
Map<String, List<String>> stdMap = new TreeMap<>();
for (Student student : students)
stdMap.computeIfAbsent(student.getCountry(), unused -> new ArrayList<>())
.add(student.getEmail());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论