I am building an object with a simple loop:
WebTarget target = getClient().target(u);
for (Entry queryParam : queryParams.entrySet()) {
There's unfortunately no foldLeft
method in the stream API. The reason for this is explained by Stuart Marks in this answer:
[...] Finally, Java doesn't provide
foldLeft
andfoldRight
operations because they imply a particular ordering of operations that is inherently sequential. This clashes with the design principle stated above of providing APIs that support sequential and parallel operation equally.
Ultimately what you're trying to do here is something procedural / sequential so I don't think the stream API is a good fit for this use case. I think the for-each loop that you have posted yourself is as good as it gets.
Update:
As @TagirValeev points out below you can in fact solve it with the stream API (using forEachOrdered. Your code would then look something like
WebTarget[] arr = { getClient().target(u) };
queryParams.entrySet()
.stream()
.forEachOrdered(e -> arr[0] = arr[0].queryParam(e.getKey(),
e.getValue()));
WebTarget target = arr[0];
I stand by my original answer though, and claim that your good old for-loop is a better approach in this case.