How to convert map to SortedMap using lambda expression in JAVA8?

For example, I have a class Student

public class Student{
    private String name;
    private int age;

    public int getAge(){
        return this.age;
    }
}

And the class School:

public class School{
    private Map<String,Student> students=new TreeMap<>();
    //stroe the index of students in the school by key is their names.

    public SortedMap<Integer,Long> countingByAge(){
        return this.students.entrySet().stream().map(s->s.getValue())
               .collect(groupingBy((Student s)->s.getAge(),counting()));
    }
}

The countingByAge method requests a return SortedMap<Integer,Long >, the key is the student's age, value is the number of students in a particular age, i.e. I need to calculate how many students are in age.

I almost finished this method, but don’t know how to convert Map<Integer,Long>to SortedMap<Integer,Long>without (SortedMap<Integer,Long>)casting.

+4
source share
1 answer

You can use groupingBy(classifier, mapFactory, downstream)and how mapFactoryto pass to the provider an instance of the Map instance that implements SortedMaphowTreeMap::new

public SortedMap<Integer, Long> countingByAge(){
    return  students.entrySet()
            .stream()
            .map(Map.Entry::getValue)
            .collect(groupingBy(Student::getAge, TreeMap::new, counting()));
}

By the way, as @Holger mentioned in the comment , you can simplify

map.entrySet()
.stream()
.map(Map.Entry::getValue)

with

map.values()
.stream()
+9

All Articles