有一个Student
类,其中包含name, surname, age
个字段和getter。
给定Student
个对象流。
如何调用collect
方法,使其返回Map
,其中age
的{{1}}为Student
,值为TreeSet
,其中包含surname
有age
的学生。
我想使用Collectors.toMap()
,但卡住了。
我以为我可以这样做并将第三个参数传递给toMap
方法:
stream().collect(Collectors.toMap(Student::getAge, Student::getSurname, new TreeSet<String>()))`.
答案 0 :(得分:8)
students.stream()
.collect(Collectors.groupingBy(
Student::getAge,
Collectors.mapping(
Student::getSurname,
Collectors.toCollection(TreeSet::new))
))
答案 1 :(得分:1)
groupingBy
收藏家的完美工作。
使用toMap
收集器的另一个解决方案是:
Map<Integer, TreeSet<String>> collect =
students.stream()
.collect(Collectors.toMap(Student::getAge,
s -> new TreeSet<>(Arrays.asList(s.getSurname())),
(l, l1) -> {
l.addAll(l1);
return l;
}));