小编yam*_*ato的帖子

如何在JAVA8中通过lambda表达式将Map转换为SortedMap?

例如,我有一个班级 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>)铸造.

java java-8 java-stream

4
推荐指数
1
解决办法
1442
查看次数

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

我有一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)

java java-8

4
推荐指数
1
解决办法
64
查看次数

标签 统计

java ×2

java-8 ×2

java-stream ×1