Skip to content
Advertisement

Check if multiple objects have same value of a field in java and remove duplicates based on other fields

So I have a list of objects. Suppose they have 2 fields startDate, endDate(data type is timestamp). So if startDate is equal to startDate of another object then I have to choose the object with higher endDate. How can I achieve this efficiently. I can use 2 for loops but that would have a high time complexity. Any better way of doing it? Thanks

Advertisement

Answer

Stream over your list, collect to map using your objects startdate as key and use a merging function to decide to which object to map if two or more objects have the same startdate by comparing the enddates. Something like:

Collection<YourObject> result =
            
yourList.stream()
        .collect(Collectors.toMap(YourObject::getStartDate,
                                  Function.identity(),
                                  (a, b) -> a.getEndDate().after(b.getEndDate()) ? a : b))
        .values();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement