有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

GroupBy之后的Java排序

我怎样才能把这些分类成一张分类地图而不是一张地图呢

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

共 (2) 个答案

  1. # 1 楼答案

    您可以在SortedMap中输入结果,如下所示:

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

    可以使用重载的^{}来获取供应商:

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