Java API Streams collecting stream in Map where value is a TreeSet

False Promise :

There is a Student class which has name, surname, age fields and getters for them.

Given a stream of Student objects.

How to invoke a collect method such that it will return Map where keys are age of Student and values are TreeSet which contain surname of students with such age.

I wanted to use Collectors.toMap(), but got stuck.

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

stream().collect(Collectors.toMap(Student::getAge, Student::getSurname, new TreeSet<String>()))`.
Eugene :
students.stream()
        .collect(Collectors.groupingBy(
                Student::getAge,
                Collectors.mapping(
                      Student::getSurname, 
                      Collectors.toCollection(TreeSet::new))           
))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459980&siteId=1