Java API streams collects streams in the map, where value is TreeSet

There is a student class with name, last name, age and getter

Given a student object stream

How to call a collect method to return a map with a key of student's age and a value of TreeSet, which contains the last names of students of this age

I want to use collectors Tomap(), but it's stuck

I thought I could do this and pass the third parameter to the tomap method:

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

Solution

students.stream()
students.stream()
        .collect(Collectors.groupingBy(
                Student::getAge,Collectors.mapping(
                      Student::getSurname,Collectors.toCollection(TreeSet::new))           
))
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>