I have a case where I want to remove objects from a list if there are duplicate ids. The items that should then be removed is the one with the oldest date. How can I do this using Java streams in a clean way? I was thinking it should be possible to like group the objects by id first and then sort them by date and only select the first object or similar but I'm struggling on how to do this.
Example:
`
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));
}
}
`