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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With