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

yam*_*ato 4 java java-8 java-stream

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

Psh*_*emo 9

您可以使用groupingBy(classifier, mapFactory, downstream)mapFactory通地图供应商实施的返回情况下SortedMapTreeMap::new

public SortedMap<Integer, Long> countingByAge(){
    return  students.entrySet()
            .stream()
            .map(Map.Entry::getValue)
            .collect(groupingBy(Student::getAge, TreeMap::new, counting()));
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,正如@Holger 在评论中提到的,你可以简化

map.entrySet()
.stream()
.map(Map.Entry::getValue)
Run Code Online (Sandbox Code Playgroud)

map.values()
.stream()
Run Code Online (Sandbox Code Playgroud)

  • `entrySet().stream().map(Map.Entry :: getValue)`是一种不必要复杂的说法`values().stream()`... (6认同)