Java8 stream cannot resolve a variable

carles xuriguera :

I am new in Java8 and I want to refactor this piece of code and convert it in a more Java8 style,

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 change it for 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:

chain cannot be resolved

Eran :

You forgot to specify the lambda expression parameter in your forEach call.

That said, you shouldn't use forEach to add elements to a collection. Use collect:

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()); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74961&siteId=1