Sort your list first on id
, then on the date
, and then on cxalap
.
Merge the sorted list into a Map
with id
as the key. In case of a conflict, keep the first record and discard others. Since the list is already sorted, this step will ensure that the first record for an id
will be kept while others will be discarded. Check Collectors.toMap to learn more about this.
Collect the stream of values of the Map
as the final List
.
List<NotificationCnavOP> result=
notificationCnavOPList
.stream()
.sorted(Comparator.comparing(NotificationCnavOP::getId)
.thenComparing(e -> LocalDate.parse(e.getDate(), DateTimeFormatter.ofPattern("dd/MM/yyyy")))
.thenComparing(NotificationCnavOP::getCxalap))
.collect(Collectors.toMap(NotificationCnavOP::getId, Function.identity(), (e1, e2) -> e1))
.values()
.stream()
.collect(Collectors.toList());
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws Exception {
List<NotificationCnavOP> notificationCnavOPList = new ArrayList<>(
Arrays.asList(
new NotificationCnavOP(1, "01/01/2000", 1),
new NotificationCnavOP(2, "01/01/2001", 2),
new NotificationCnavOP(2, "01/01/2002", 3),
new NotificationCnavOP(2, "01/01/2001", 2)));
List<NotificationCnavOP> result =
notificationCnavOPList
.stream()
.sorted(Comparator.comparing(NotificationCnavOP::getId)
.thenComparing(e -> LocalDate.parse(e.getDate(), DateTimeFormatter.ofPattern("dd/MM/yyyy")))
.thenComparing(NotificationCnavOP::getCxalap))
.collect(Collectors.toMap(NotificationCnavOP::getId, Function.identity(), (e1, e2) -> e1))
.values()
.stream()
.collect(Collectors.toList());
System.out.println(result);
}
}
class NotificationCnavOP {
private int id;
private String date;
private int cxalap;
public NotificationCnavOP(int id, String date, int cxalap) {
this.id = id;
this.date = date;
this.cxalap = cxalap;
}
public int getId() {
return id;
}
public String getDate() {
return date;
}
public int getCxalap() {
return cxalap;
}
@Override
public String toString() {
return "[" + id + ", " + date + ", " + cxalap + "]";
}
}
Output:
[[1, 01/01/2000, 1], [2, 01/01/2001, 2]]
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.