在JAVA8中通过lambda表达式将Map转换为SortedM

在JAVA8中通过lambda表达式将Map转换为SortedM

本文介绍了如何在JAVA8中通过lambda表达式将Map转换为SortedMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个类 Student

public class Student{
    private String name;
    private int age;

    public int getAge(){
        return this.age;
    }
}

和一个类学校:

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()));
    }
}

countingByAge方法要求返回 SortedMap< Integer,Long> ,关键是学生的年龄,值是每个不同年龄的学生人数,即我需要计算每个年龄段的学生很多.

The countingByAge method ask for return of a SortedMap<Integer,Long >, the key is the age of student, value is the number of students per distinct age, i.e. I need to count how many students per age.

我几乎完成了该方法,但是我不知道如何在没有的情况下将 Map< Integer,Long> 转换为 SortedMap< Integer,Long> >(SortedMap< Integer,Long>)投射.

I have almost finished the method, but I don't know how to transform the Map<Integer,Long> to SortedMap<Integer,Long> without (SortedMap<Integer,Long>) casting.

推荐答案

您可以使用 groupingBy(分类器,mapFactory,下游) 并作为 mapFactory 传递实现了 SortedMap 的Map的供应商返回实例,例如 TreeMap :: new

You can use groupingBy(classifier, mapFactory, downstream) and as mapFactory pass Supplier returning instance of Map implementing SortedMap like TreeMap::new

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

BTW,如 @Holger ,您可以简化

BTW, as @Holger mentioned in comment you can simplify

map.entrySet()
.stream()
.map(Map.Entry::getValue)

map.values()
.stream()

这篇关于如何在JAVA8中通过lambda表达式将Map转换为SortedMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 20:50