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
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
The execution result will be displayed as:
{25=Person{name='Alice', age=25}, 30=Person{name='Bob', age=30}}