Home » Java » Java Sort after GroupBy-Exceptionshub

Java Sort after GroupBy-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

How can I sort these into a SortedMap instead of just a 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));
How to&Answers:

You can use the overloaded groupingBy() that takes a supplier:

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

Answer:

You could feed the result in a SortedMap like so:

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