lambda表达式:将函数结果用作Map中的下一个参数

insrf1ej  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(328)

我的Map器中有一个带有几个参数的函数:函数(a,b,c)它们都来自不同的函数,都在同一个服务中,但是参数b和c需要参数a的结果

service.getRequests()
            .stream()
            .map(r ->
                mapper.function(
                    service.getAList(r), //return List<A> aList
                    service.getBList(aList), //use the previous aList as parameter
                    service.getCList(aList) //same
            )
            .sorted()
            .collect(Collectors.toList());

有办法做到这一点吗?

xzv2uavs

xzv2uavs1#

照办

.map(r -> {
    List<A> aList = service.getAList(r);
    return mapper.function(
        aList,
        service.getBList(aList),
        service.getCList(aList);
})
pgpifvop

pgpifvop2#

最好将此功能移动到单独的方法中:

private MapperResult remap(Request request) {
    List<A> resultA = service.getAList(request);

    return mapper.function(
        resultA,
        service.getBList(resultA),
        service.getCList(resultA)
    );
}

然后引用此方法:

service.getRequests()
       .stream()
       .map(MyClass::remap)
       .sorted()
       .collect(Collectors.toList());

相关问题