Given an order class like:
@ToString
@AllArgsConstructor
@Getter
static class Order {
long customerId;
LocalDate orderDate;
}
and a list of orders:
List<Order> orderList = List.of(new Order(1, LocalDate.of(2020,Month.APRIL,21)),
new Order(1, LocalDate.of(2021,Month.APRIL,21)),
new Order(1, LocalDate.of(2022,Month.APRIL,21)),
new Order(2, LocalDate.of(2020,Month.APRIL,21)),
new Order(2, LocalDate.of(2021,Month.APRIL,21)),
new Order(3, LocalDate.of(2020,Month.APRIL,21)),
new Order(3, LocalDate.of(2022,Month.APRIL,21)),
new Order(4, LocalDate.of(2020,Month.APRIL,21)));
I need to get a list of customerId where last orderDate is older than 6 months. So for above example [2,4]. My idea is to first to group by customerId, second map to last orderDate and third to filter those which are older than 6 months. I am stuck at second step on how to map to a single order with the recent orderDate
First step
Map<Long, List<Order>> grouped =
orderList.stream()
.collect(Collectors.groupingBy(Order::getCustomerId));
Second step (stuck here how to change the above to get only one item as value)
Map<Long, Order> grouped =
orderList.stream()
.collect(Collectors.groupingBy(Order::getCustomerId, ???));
or even better
Map<Long, LocalDate> grouped =
orderList.stream()
.collect(Collectors.groupingBy(Order::getCustomerId, ???));
I have tried to use Collectors.mapping() , Collectors.reducing() and Collectors.maxBy() but having a lot of compile errors.