共計 1155 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Java 中可以使用 Stream API 來分組、排序和取第一個值。以下是一個示例代碼:
假設(shè)有一個 List<Person> 對象列表,每個 Person 對象有兩個屬性:name 和 age。現(xiàn)在要按照 age 屬性分組并且按照 name 屬性排序,然后取每個分組的第一個值。
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 + "}";
}
}
在上面的代碼中,首先使用 stream() 方法將 List<Person> 轉(zhuǎn)換為 Stream<Person>,然后使用 collect() 方法對 Stream 進(jìn)行分組和集合。在分組時,使用 Collectors.groupingBy() 方法按照 age 屬性進(jìn)行分組,然后對每個分組使用 Collectors.collectingAndThen() 方法來獲取每個分組的第一個值,通過比較 name 屬性的大小來確定第一個值。最后將結(jié)果打印出來。
運行結(jié)果將會輸出:
{25=Person{name='Alice', age=25}, 30=Person{name='Bob', age=30}}
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完