The Java 8 stream cannot resolve variables

I'm new to Java 8. I want to refactor this code and convert it into more Java 8 styles,

for (RestaurantAddressee RestaurantAddressee : consultationRestaurant.getAddressees()) {
            Chain chain = chainRestService.getClient().getChainDetails(getTDKUser(),RestaurantAddressee.getChain().getId());
            if (chain.getOrganisation().getId().equalsIgnoreCase(event.getOrganisationId())) {
                chainIds.add(restaurantAddressee.getChain().getId());
            }
        }

So I changed this Code:

consultationRestaurant.getAddressees()
        .stream()
        .map( ma -> chainRestService.getClient().getChainDetails(getTDKUser(),ma.getChain().getId()))
        .filter(chain -> chain.getOrganisation().getId().equalsIgnoreCase(event.getOrganisationId()))
        .forEach(chainIds.add(chain.getId()));

But I have this compilation error:

The chain cannot be solved

Solution

You forgot to specify the lambda expression parameter in the foreach call

That is, you should not use foreach to add elements to the collection Use collection:

List<String> chainIds =
    consultationRestaurant.getAddressees()
        .stream()
        .map( ma -> chainRestService.getClient().getChainDetails(getTDKUser(),ma.getChain().getId()))
        .filter(chain -> chain.getOrganisation().getId().equalsIgnoreCase(event.getOrganisationId()))
        .map(Chain::getId)
        .collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>