BAR
BAR

Reputation: 17121

Java Sort after GroupBy

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

Upvotes: 0

Views: 95

Answers (2)

Jan Held
Jan Held

Reputation: 654

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

Upvotes: 3

Kartik
Kartik

Reputation: 7917

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

Upvotes: 3

Related Questions