英文:
Rewrite Imperative For Loop With Declarative Approach using Java Stream API
问题
以下是用Java Streams API 重写的代码:
public WebTarget attachQueryParams(List<NameValuePair> queryParams, WebTarget webTarget) {
return queryParams.stream()
.reduce(webTarget, (wt, pair) -> wt.queryParam(pair.getName(), pair.getValue()),
(wt1, wt2) -> {
throw new UnsupportedOperationException("Combiner not implemented");
});
}
请注意,我在这里添加了一个未实现的组合器(combiner),因为在这种情况下,不需要组合操作。如果你有多个线程运行这个代码,可能需要实现一个正确的组合器。但是,对于大多数情况,你可以保留它未实现,因为这个操作不会被执行。
英文:
I have list of http query params in NamveValuePair
format and a WebTarget
(javax/ws/rs/client/WebTarget.java). Then I am simply attaching those query params to WebTarget
one by one using imperative approach.
I know that it's easy to apply stream when all the elements are in the data type. But I failed to apply the same solution when they are not.
This is the code I wan to rewrite using Java Streams API
public WebTarget attachQueryParams(List<NameValuePair> queryParams, WebTarget webTarget) {
for (NameValuePair param : queryParams) {
webTarget = webTarget.queryParam(param.getName(), param.getValue());
}
return webTarget;
}
I tried to rewrite it using stream reduce
function as follows with no luck so far:
queryParams.stream().reduce(webTarget,((webTarget1, pair) -> webTarget1.queryParam(pair.getName(),pair.getValue())))
答案1
得分: 3
你可以尝试类似这样的写法:
queryParams.stream()
.reduce(webTarget,
(webTarget1, pair) -> webTarget1.queryParam(pair.getName(),pair.getValue()),
(v1, v2) -> v1);
为什么需要第三个参数,你可以在这里找到答案。
英文:
You can try something like this:
queryParams.stream()
.reduce(webTarget,
(webTarget1, pair) -> webTarget1.queryParam(pair.getName(),pair.getValue()),
(v1, v2) -> v1);
Why you need third parameter you can find out here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论