我有一个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();
}
}
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());
}
}
方法countingRewardsPerStudent
需要返回List<String>
,其中包含学生的姓名和学生的奖励数量,如Name has rewards:###
。
我对return
行感觉很好,但是我坚持使用groupingBy((Student s)->s.getName(),XXXX)
,我已经尝试了很多方法来执行XXXX
,但这并不好。任何帮助将不胜感激。
答案 0 :(得分:6)
如果两个学生的名字相同,你需要决定该怎么做 - 假设你想要加上他们的奖励,它可能看起来像:
scope.customParam
如果您没有多名具有指定姓名的学生,您可以这样做:
.collect(groupingBy(Student::getName, summingInt(Student::countRewards)));