AdamIJK
AdamIJK

Reputation: 655

Get value from nested list using lambda operators java 8

I am having a Order entity which contains list of items with in it, from that I need to loop list of orders and each order contains list of items, i need to extract Items alone from that items i need to extract single item quantity here my code

public class order{
    private Integer orderId;
    private String orderNo;
    .
    .
    private List<item> items;
    .
    .
    .
}

public class item{
    private Integer itemId;
    private String itemCode;
    private String itemDescription;
    private BigDecimal cost;
    .
    .
    .
}

How to iterate this in java8?

Upvotes: 0

Views: 2512

Answers (2)

rorschach
rorschach

Reputation: 2947

Your explanation is confusing.

If you have a single Order with Items that you need to loop over, it's really easy:

Order singleOrder;

singleOrder.getItems().stream()
    .//whatever else you need;

If you have a List of Orders, it's still really easy:

List<Order> multipleOrders;

multipleOrders.stream()
    .map(Order::getItems)
    .flatMap(List::stream)
    .//whatever else you need

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

If you have a:

List<Order> list = ...

you could .flatMap() the nested list(s) of Item objects with:

List<Item> allItems = list.stream()
                          .map(Order::getItems)
                          .flatMap(List::stream)
                          .distinct()
                          .collect(Collectors.toList());

Upvotes: 2

Related Questions