javalistjava-streamgrouping

Java 8 Streams remove duplicate entries, keeping the element with the min date


I have Java beans like:

class OrderDeatils {
    Long orderId;
    Long userId;
    OrderInfo info;

    // Required getters/setters
}

class OrderInfo {
    OffsetDateTime orderCreatedDate;
    
    // Required getter/setter
}

I have data as List<OrderDeatils> list:

orderId.   userId.  OrderInfo[orderCreatedDate]. 
1001.       123.      2015/07/07 
1002.       124.      2015/08/07 
1003.       125.      2015/09/07 
1004.       123.      2015/08/07 

How, I can remove duplicate entry based on userId and keep data with min date as below:

orderId.   userId.  OrderInfo[orderCreatedDate]. 
1001.       123.      2015/07/07 
1002.       124.      2015/08/07 
1003.       125.      2015/09/07 

Should return a list of whole OrderDeatils objects.

I tried like:

 list.stream().collect(
                Collectors.groupingBy(OrderDeatils::getUserId,
                        Collectors.collectingAndThen(
                                Collectors.reducing((OrderDeatils d1, OrderDeatils d2)
                                        -> d1.getInfo.getOrderCreatedDate().isBefore(d2.getInfo.getOrderCreatedDate()) ? d1 : d2), Optional::get)));

But the response is not as expected, I am not getting updated List<OrderDeatils> as output.


Solution

  • I will not write the code for you, but here are the steps:

    ...collect(Collectors.toMap(
         OrderDeatils::getUserId,
         Function.identity(),
         (left, right) ->
            left.getInfo.getOrderCreatedDate().isBefore(right.getInfo.getOrderCreatedDate()) ? left : right        
    ))