Java Stream: Group, Sort, Get First Value

In Java, you can utilize the Stream API to group, sort, and retrieve the first value. Here is an example code:

Suppose there is a list of objects of type List, each Person object having two properties: name and age. Now, the goal is to group by age property and sort by name property within each group, and then retrieve the first value from each group.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> personList = List.of(
                new Person("Alice", 25),
                new Person("Bob", 30),
                new Person("Charlie", 25),
                new Person("David", 30)
        );

        Map<Integer, Person> result = personList.stream()
                .collect(Collectors.groupingBy(Person::getAge,
                        Collectors.collectingAndThen(Collectors.minBy((p1, p2) -> p1.getName().compareTo(p2.getName())), p -> p.get())));

        System.out.println(result);
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

In the code above, the List is first converted to a Stream using the stream() method, and then grouping and collecting is done on the Stream using the collect() method. During grouping, the groupingBy() method from Collectors is used to group by age property, and then the collectingAndThen() method from Collectors is used to get the first value of each group by comparing the size of the name property. Finally, the results are printed out.

The execution result will be displayed as:

{25=Person{name='Alice', age=25}, 30=Person{name='Bob', age=30}}
bannerAds