Closing over immutable variable and accumulate values across multiple iterations as a lambda expression - Java 8

丶灬走出姿态 提交于 2019-12-02 04:16:28

If you want functional approach you need foldLeft(right) or reduce.

foldLeft is implemented in some libraries, for example Functionaljava and streamEx.

Functionaljava:

<B> B foldLeft(final F<B, F<A, B>> bff, final B z)

WebTarget wt = wtCollection.foldLeft(x -> (y -> x.queryParam(...)), new WebTarget());

StreamEx:

<U> U foldLeft(U seed, BiFunction<U, ? super T, U> accumulator) 

UPD stream-reduce

queryMap.entrySet().stream()
    .reduce(new WebTarget(), (x, y) -> { 
        x.queryParam(y.getKey(), y.getValue()); 
    });

You can use the ol' array trick, which is not good for anything more than a proof of concept.

WebTarget[] webTarget = {client.target(this.address.getUrl()).path(path)};
if (queryMap != null){
    queryMap.forEach((k, v)->{
        webTarget[0] =  webTarget[0].queryParam(k, v);
    });
}
return webTarget[0];

You could improve it by using an AtomicReference.

AtomicReference<WebTarget> webTarget = new AtomicReference<>(client.target(this.address.getUrl()).path(path));
if (queryMap != null){
    queryMap.forEach((k, v)->{
        webTarget.updateAndGet(w->w.queryParam(k, v));
    });
}
return webTarget.get();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!