Java API Streams在Map中收集流,其中value是TreeSet

时间:2018-02-04 14:47:15

标签: java java-8 java-stream collectors

有一个Student类,其中包含name, surname, age个字段和getter。

给定Student个对象流。

如何调用collect方法,使其返回Map,其中age的{​​{1}}为Student,值为TreeSet,其中包含surnameage的学生。

我想使用Collectors.toMap(),但卡住了。

我以为我可以这样做并将第三个参数传递给toMap方法:

stream().collect(Collectors.toMap(Student::getAge, Student::getSurname, new TreeSet<String>()))`.

2 个答案:

答案 0 :(得分:8)

students.stream()
        .collect(Collectors.groupingBy(
                Student::getAge,
                Collectors.mapping(
                      Student::getSurname, 
                      Collectors.toCollection(TreeSet::new))           
))

答案 1 :(得分:1)

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;
                        }));