在Java中可以使用Stream API来分组、排序和取第一个值。以下是一个示例代码:
假设有一个List
import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { ListpersonList = List.of( new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 25), new Person("David", 30) ); Map 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 + "}"; } }
在上面的代码中,首先使用stream()方法将List
运行结果将会输出:
{25=Person{name='Alice', age=25}, 30=Person{name='Bob', age=30}}