首页 > 解决方案 > Java8 流无法解析变量

问题描述

我是 Java8 的新手,我想重构这段代码并将其转换为更 Java8 的风格,

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

所以我为此代码更改它:

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

但我有这个编译错误:

链无法解决

标签: javajava-8java-stream

解决方案


您忘记在forEach调用中指定 lambda 表达式参数。

也就是说,您不应该使用forEach将元素添加到集合中。使用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()); 

推荐阅读