0

I am trying to convert normal Java code to Streams but failing to do so. Can anyone please help here?

Here's the code I am trying to convert

Set<Strings> restrictedValues = getRestrictedValues();
for (Customer customer : request.getCustomers()) {
    for (Order order : customer.getOrders()) {
        for (String restrictedValue : restrictedValues) {
            if (order.isItemExcluded(restrictedValue)) {
                response.setExcludedItem(order.getId());
            }
            if (treatment.isItemIncluded(restrictedValue)) {
                response.setIncludedItem(order.getId());
            }
        }
    }
}

What I have done so far is below, I am kinda lost here.

request.getCustomers().stream()
  .forEach(customer->{
     customer.getOrders().stream()
         .forEach(order->{
             order.isItemExcluded(restrictedValue)
                 }).collect(????) //What to do now });</code>
shmosel
  • 49,289
  • 6
  • 73
  • 138
Mayank
  • 3
  • 1
  • 1
    Just don't `collect` at all. `forEach` is a terminal operation. – Unmitigated Mar 29 '23 at 04:56
  • Does this answer your question? [What's the difference between map() and flatMap() methods in Java 8?](https://stackoverflow.com/questions/26684562/whats-the-difference-between-map-and-flatmap-methods-in-java-8) – Torben Mar 29 '23 at 04:57

2 Answers2

0

You can use flatMap and use forEach terminal operation as,


request.getCustomers()
        .stream()
        .flatMap(customer -> customer.getOrders().stream())
        .forEach(order -> restrictedValues.forEach(restrictedValue -> {
            if (order.isItemExcluded(restrictedValue)) {
                response.setExcludedItem(order.getId());
            }
            if (treatment.isItemIncluded(restrictedValue)) {
                response.setIncludedItem(order.getId());
            }
        }));
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0
request.getCustomers()
                .stream()
                .flatMap(customer -> customer.getOrders().stream())
                .forEach(order -> {
                    if(restrictedValues.stream().anyMatch(order::isItemExcluded))
                        response.setExcludedItem(order.getId());
                    if(restrictedValues.stream().anyMatch(order::isItemIncluded))
                        response.setIncludedItem(order.getId());
                }));
Thomson Ignesious
  • 689
  • 1
  • 8
  • 25