Java8流无法解析变量

Java8流无法解析变量,java,java-8,java-stream,Java,Java 8,Java Stream,我是Java8新手,我想重构这段代码,并将其转换为更具Java8风格的代码 for (RestaurantAddressee RestaurantAddressee : consultationRestaurant.getAddressees()) { Chain chain = chainRestService.getClient().getChainDetails(getTDKUser(), RestaurantAddressee.getChain().getId()

我是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()));     
但我有一个编译错误:


无法解析链

您忘记在
forEach
调用中指定lambda expression参数

也就是说,您不应该使用
forEach
将元素添加到集合中。使用
收集

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()); 
列出链ID=
consultationRestaurant.getAddressees()
.stream()
.map(ma->chainRestService.getClient().getChainDetails(getdkuser(),ma.getChain().getId())
.filter(chain->chain.getOrganization().getId().equalsIgnoreCase(event.getOrganizationID())
.map(链::getId)
.collect(Collectors.toList());

这里。您的循环定义:

Chain chain = chainRestService.getClient()...
但是您的stream语句没有定义该变量

因此:在需要该变量的地方,您必须提供,例如作为参数:

filter(chain -> chain.getOrganisation().getId().equalsIgnoreCase(event.getOrganisationId()))

.forEach(chain->chainIds.add(chain.getId())
您可以使用collector.collect(collector.toList())稍微解释一下Hadi的评论:lambda中的变量声明仅对该lambda有效,即,即使您在传递给
filter()
的lambda中定义了
chain
,该变量在
forEach()
中不可见。您的forEach语法错误,看看医生。使用第一个代码段比使用第二个包含大量lambda的代码段要好得多。