我有一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)
该方法countingRewardsPerStudent需要返回List<String>包含学生姓名和学生奖励数量的a Name has rewards:###.
我对这return条线很好,但是我坚持了groupingBy((Student s)->s.getName(),XXXX),我已经尝试了很多方法来表现XXXX,但这并不好.任何帮助将不胜感激.
如果两个学生的名字相同,你需要决定该怎么做 - 假设你想要加上他们的奖励,它可能看起来像:
.collect(groupingBy(Student::getName, summingInt(Student::countRewards)));
Run Code Online (Sandbox Code Playgroud)
如果您没有多名具有指定姓名的学生,您可以这样做:
.collect(toMap(Student::getName, Student::countRewards));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |