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

前端 未结 2 2063
长情又很酷
长情又很酷 2021-01-24 09:56

WebTarget in Jersey client is implemented as a immutable object, and any operations to change the state returns a new WebTarget. To add query params to it, which is coming in as

2条回答
  •  滥情空心
    2021-01-24 10:49

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

提交回复
热议问题