-3

I read through several threads about operating on the nested java collections using Lambda but none addressed my specific situation, although this one came close and then took off to a different direction (flatMap). Please show me how to write the following code in Lambda.

 for(AppUser user : users){
     List<CustomerOrder> orders = user.getOrders();
     for(CustomerOrder order : orders){
             order.setConsumer(user);
             List<LineItem> items = order.getLineItems();
             for (LineItem item : items){
                  item.setOrder(order);
             }
     }
 }

Thanks

2 Answers2

0

If all you want to do is iterate, the forEach method on either the Stream.java or the Iterable.java should be enough. Here is the "streamy" way of doing what you are trying to do with the for loops

users.stream().forEach( user ->
        user.getOrders().stream().forEach( order -> {
            order.setConsumer(user);
            order.getLineItems().stream().forEach(
                    lineItem -> lineItem.setOrder(order)
            );
        }
));

Although you don't really need to convert the iterable returned by by those getters to streams.

0

This is a solution I came up with but I see that Smarth Ktyal already posted an answer.

users
                    .stream()
                    .forEach(e->e.getOrders()
                            .stream()
                            .forEach(k->{
                                k.setConsumer(e);
                                k.getLineItems()
                                    .stream()
                                    .forEach(l->l.setOrder(k));
                                }
                            )
                    );