Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a Map to a SortedMap by 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 a 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 ask for return of a SortedMap<Integer,Long >, the key is the age of student, value is the number of students per distinct age, i.e. I need to count how many students per age.

I have almost finished the method, but I don't know how to transform the Map<Integer,Long> to SortedMap<Integer,Long> without (SortedMap<Integer,Long>) casting.

like image 397
yamato Avatar asked Jul 06 '15 14:07

yamato


People also ask

Does HashMap implement SortedMap interface?

The class which implements the SortedMap interface is TreeMap. TreeMap class which is implemented in the collections framework is an implementation of the SortedMap Interface and SortedMap extends Map Interface.


1 Answers

You can use groupingBy(classifier, mapFactory, downstream) and as mapFactory pass Supplier returning instance of Map implementing SortedMap like TreeMap::new

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

BTW, as @Holger mentioned in comment you can simplify

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

with

map.values()
.stream()
like image 75
Pshemo Avatar answered Nov 14 '22 23:11

Pshemo