首页 > 解决方案 > GroupBy 之后的 Java 排序

问题描述

如何将这些排序为 SortedMap 而不仅仅是 Map?

    class Person {
        String name;
        double weight;

        public Person(String name, double weight) {
            this.name = name;
            this.weight = weight;
        }

        public double getWeight() {
            return this.weight;
        }
    }
    List<Person> people = Arrays.asList(
            new Person("Alex", 150.0),
            new Person("Courtney", 120.0),
            new Person("Billy", 180.0)
            );

    Map<Double, List<Person>> grouped = people.stream()
            .collect(Collectors.groupingBy(Person::getWeight));

标签: java

解决方案


您可以SortedMap像这样提供结果:

final Map<Double, List<Person>> grouped = new TreeMap<>(
    people.stream().collect(Collectors.groupingBy(Person::getWeight)));

推荐阅读