Turdaliev Nursultan
Turdaliev Nursultan

Reputation: 2576

Rewrite Imperative For Loop With Declarative Approach using Java Stream API

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

Upvotes: 1

Views: 429

Answers (1)

lczapski
lczapski

Reputation: 4120

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

Upvotes: 3

Related Questions