例如,我有一个类
countingByAge方法要求返回一个SortedMap,其中key是学生的年龄,value是每个不同年龄的学生人数,即我需要计算每个年龄有多少学生。
我已经快完成这个方法了,但我不知道如何将Map转换为SortedMap而不使用(SortedMap)强制转换。
Student
。public class Student{
private String name;
private int age;
public int getAge(){
return this.age;
}
}
还有一个名为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()));
}
}
countingByAge方法要求返回一个SortedMap,其中key是学生的年龄,value是每个不同年龄的学生人数,即我需要计算每个年龄有多少学生。
我已经快完成这个方法了,但我不知道如何将Map转换为SortedMap而不使用(SortedMap)强制转换。
grouping
收集器返回的Map
不是一个SortedMap
。 - Holger