使用Java Stream API以声明性方法重写带有命令式for循环的代码:

huangapple go评论85阅读模式
英文:

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&lt;NameValuePair&gt; 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) -&gt; 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) -&gt; webTarget1.queryParam(pair.getName(),pair.getValue()),
                (v1, v2) -&gt; v1);

Why you need third parameter you can find out here

huangapple
  • 本文由 发表于 2020年4月10日 15:49:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/61136070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定