如何在java8中的“groupingBy”中的逗号后面编写代码?

时间:2015-07-06 16:43:11

标签: java java-8

我有一个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,但这并不好。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:6)

如果两个学生的名字相同,你需要决定该怎么做 - 假设你想要加上他们的奖励,它可能看起来像:

scope.customParam

如果您没有多名具有指定姓名的学生,您可以这样做:

.collect(groupingBy(Student::getName, summingInt(Student::countRewards)));