[英]How to write the code after the comma within this “groupingBy” in java8?
我有一个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
,但这并不好。 任何帮助将不胜感激。
如果两个学生的名字相同,你需要决定该怎么做 - 假设你想要加上他们的奖励,它可能看起来像:
.collect(groupingBy(Student::getName, summingInt(Student::countRewards)));
如果您没有多名具有指定姓名的学生,您可以这样做:
.collect(toMap(Student::getName, Student::countRewards));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.