Java API Streams 在 Map 中收集流,其中值为 TreeSet
Java API Streams collecting stream in Map where value is a TreeSet
有一个 Student
class,它有 name, surname, age
个字段和它们的吸气剂。
给定一个 Student
对象流。
如何调用 collect
方法,使其 return Map
其中键是 Student
的 age
,值是 TreeSet
其中包含 surname
的学生age
。
我想使用 Collectors.toMap()
,但卡住了。
我想我可以这样做并将第三个参数传递给 toMap
方法:
stream().collect(Collectors.toMap(Student::getAge, Student::getSurname, new TreeSet<String>()))`.
students.stream()
.collect(Collectors.groupingBy(
Student::getAge,
Collectors.mapping(
Student::getSurname,
Collectors.toCollection(TreeSet::new))
))
Eugene 提供了您想要的最佳解决方案,因为它是 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;
}));
有一个 Student
class,它有 name, surname, age
个字段和它们的吸气剂。
给定一个 Student
对象流。
如何调用 collect
方法,使其 return Map
其中键是 Student
的 age
,值是 TreeSet
其中包含 surname
的学生age
。
我想使用 Collectors.toMap()
,但卡住了。
我想我可以这样做并将第三个参数传递给 toMap
方法:
stream().collect(Collectors.toMap(Student::getAge, Student::getSurname, new TreeSet<String>()))`.
students.stream()
.collect(Collectors.groupingBy(
Student::getAge,
Collectors.mapping(
Student::getSurname,
Collectors.toCollection(TreeSet::new))
))
Eugene 提供了您想要的最佳解决方案,因为它是 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;
}));