例如,我有一个班级 Student
public class Student{
private String name;
private int age;
public int getAge(){
return this.age;
}
}
Run Code Online (Sandbox Code Playgroud)
一节课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()));
}
}
Run Code Online (Sandbox Code Playgroud)
countingByAge方法要求返回a SortedMap<Integer,Long >,关键是学生的年龄,值是每个不同年龄的学生数,即我需要计算每个年龄的学生数.
我已经几乎完成了方法,但我不知道如何转换Map<Integer,Long>到SortedMap<Integer,Long>无(SortedMap<Integer,Long>)铸造.
我有一Student节课:
public class Student{
private String name;
private Map<String,Reward> rewards=new HashMap<>();
//stores the rewards that the student got,key is reward's name.
public String getName(){
return this.name;
}
public int countRewards(){//just counts the #of rewards
return this.rewards.size();
}
}
Run Code Online (Sandbox Code Playgroud)
和School班级:
public class School{
private Map<String,Student> students=new TreeMap<>();
//Stores the students in the school,key is student's name.
public List<String> countingRewardsPerStudent(){
Map <String,Integer>step1=
this.students.values().stream()
.sorted(comparing(Student::countRewards).reversed().thenComparing(Student::getName))
.collect(groupingBy((Student s)->s.getName(), //Error
(Student s)->s.countRewards() //here !!!!!
));
return step1.entrySet().stream().map(s->s.getKey()+" has rewards:"+s.getValue())
.collect(toList());
} …Run Code Online (Sandbox Code Playgroud)