How I can do this more better using lambda?

Viewed 124

I don't like section with forEach, but I wouldn't know how to do this better with lambda.

list1.stream().map(element -> {
    list2.forEach(item -> {
       if (element.getKey().equals(item.getKeyNextYear())) {
          element.setSummPreviosYear(item.getSumm());
          element.setCashboxCountPreviosYear(item.getCashboxCount());
          element.setCheckCountPreviosYear(item.getCheckCount());
          element.setArticleCountPreviosYear(item.getArticleCount());
       }
    });
    return element;
}).collect(Collectors.toList());
2 Answers

You can simplify this a lot by removing the outer stream and doing the inner part with a filter().findAny() search. This also prevents re-setting the properties in case multiple items in list2 match the element.

list1.forEach(element ->
                list2.stream()
                     .filter(item -> element.getKey().equals(item.getKeyNextYear()))
                     .findAny()
                     .ifPresent(item -> {
                         element.setSummPreviosYear(item.getSumm());
                         element.setCashboxCountPreviosYear(item.getCashboxCount());
                         element.setCheckCountPreviosYear(item.getCheckCount());
                         element.setArticleCountPreviosYear(item.getArticleCount());
                     }));

There is no need to stream list1 and collect it into a new list, at least it isn't clear from your sample code. The original list will still contain the same elements as the new one, including the changed properties.

To remove 'if' - statement you can use filter first:

list2.filter(item -> element.getKey().equals(item.getKeyNextYear())).forEach(...)

And, I think, It's better to move setters to new method

Related