It is possible to rewrite the following cycle using stream api or am I trying in vain?

Viewed 77

Main object:

public class Order {
    private Long orderId;
    ...
    private List<OrderAudit> auditList;
}

Item object of Order

public class OrderAudit {
    private Long orderId;
    ...
}

All orders

List<Order> orderList = orderDao.getOrderList(request);

All items

List<OrderAudit> allAudits = orderDao.getAllAudits();

There I try to find all audits of each order and set this list to order. Cycle:

for (Order order : orderList) {
    Long orderId = order.getOrderId();

    List<OrderAudit> orderAuditList = allAudits.stream()
                                               .filter(x-> x.getOrderId().equals(orderId))
                                               .collect(Collectors.toList());
    order.setAuditList(orderAuditList);
}
1 Answers

You can use groupingBy to create map of List<OrderAudit> by orderId

Map<Long, List<OrderAudit>> orderAuditMap = allAudits.stream()
            .collect(Collectors.groupingBy(OrderAudit::getOrderId));

If you want to preserve order of OrderAudit

Map<Long, List<OrderAudit>> orderAuditMap = allAudits.stream()
                .collect(Collectors.groupingBy(i -> i.getOrderId(), LinkedHashMap::new, Collectors.toList()));

Then get List<OrderAudit> by orderId from map and set in order using forEach()

orderList.stream().forEach(e -> e.setAuditList(orderAuditMap.get(e.getOrderId())));
Related