如果有重復的 id,我想從串列中洗掉物件。然后應該洗掉的專案是日期最早的專案。如何以干凈的方式使用 Java 流來做到這一點?我在想應該可以先按 id 對物件進行分組,然后按日期對它們進行排序,并且只選擇第一個物件或類似物件,但我正在努力解決如何做到這一點。
例子:
`
package org.example;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
class Student {
private String id;
private LocalDateTime startDatetime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public LocalDateTime getStartDatetime() {
return startDatetime;
}
public void setStartDatetime(LocalDateTime startDatetime) {
this.startDatetime = startDatetime;
}
public Student(String id, LocalDateTime startDatetime) {
this.id = id;
this.startDatetime = startDatetime;
}
}
public static void main(String[] args) {
new Main();
}
public Main() {
List<Student> students = new ArrayList<>() {
{
add(new Student("1", LocalDateTime.now()));
add(new Student("1", LocalDateTime.of(2000, 02, 01, 01, 01)));
add(new Student("1", LocalDateTime.of(1990, 02, 01, 01, 01)));
add(new Student("2", LocalDateTime.of(1990, 02, 01, 01, 01)));
} };
//Now this list should be sorted as the following:
//If two or more student objects have the same id, remove the ones with the oldest startDateTime.
//Thus, the result above should only contain 2 objects. The first object with id 1 and the LocalDateTime.now() and the second object should be the one with id 2.
Map<String, List<Student>> groupedStudents =
students.stream().collect(Collectors.groupingBy(Student::getId));
}
}
`
uj5u.com熱心網友回復:
為了從串列中消除重復的學生(即具有相同的學生id),我們可以使用輔助地圖。
此 Map 應將(具有最新開始日期的那個)的單個實體Student與特定的id. 用于該目的的正確收集器是一個三引數版本,toMap()它期望:
- 一個keyMapper ,它從消費的流元素中生成一個鍵;
- 一個valueMapper生成一個值;
- 和一個負責解決重復的mergeFunction 。
為了實作mergeFunction,我們可以使用靜態方法BinaryOperator.maxBy,它需要一個比較器作為引數。為了定義一個比較器,我們可以使用 Java 8 Comparator.comparing()。
最后,要生成具有唯一性的學生串列,id我們需要在中間 Map 的值上生成一個流,應用排序將元素收集到一個串列中。
List<Student> students = List.of(
new Student("1", LocalDateTime.now()),
new Student("1", LocalDateTime.of(2000, 02, 01, 01, 01)),
new Student("1", LocalDateTime.of(1990, 02, 01, 01, 01)),
new Student("2", LocalDateTime.of(1990, 02, 01, 01, 01))
);
List<Student> uniqueStudents = students.stream()
.collect(Collectors.toMap(
Student::getId,
Function.identity(),
BinaryOperator.maxBy(Comparator.comparing(Student::getStartDatetime))
))
.values().stream()
.sorted(Comparator.comparing(Student::getStartDatetime))
.toList(); // for Java 16 .or collect(Collectors.toList())
輸出:
Student{id='2', startDatetime=1990-02-01T01:01}
Student{id='1', startDatetime=2022-11-01T14:03:17.858753}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524701.html
標籤:爪哇排序java流过滤
上一篇:按陣列值在黑名單陣列中的存在對陣列值進行排序,然后按字母順序
下一篇:更改排序時過濾不會自動作業
