Suppose I have varargs method that I'm trying to build Foo that uses builder pattern
public Foo buildSomething(String... attributes) {
return Foo.builder()
.attribute(attributes[0])
.attribute(attributes[1])
.attribute(attributes[2])
...
.build()
}
Obviously, this does not work. Can it be done with streams?
FooBuilder builder = Foo.builder();
for (String attribute : attributes) {
builder = builder.attribute(attribute);
}
return builder.build();
Calling builder =
in the for loop is usually not necessary, but this way you don't make any assumptions about the builder returning the same instance or not.
You can do this with streams but I think it is unnecessary given the requirements:
FooBuilder builder = Foo.builder();
Arrays.stream(attributes)
.forEach(builder::attribute);
return builder.build();
I would only recommend using streams if you need to use some of the other intermediate/filter methods. Otherwise you are probably creating unnecessary allocations. You are also unable to update/reassign the builder variable unless you use something like AtomicReference
or a one-element array:
FooBuilder[] builder = {Foo.builder()};
Arrays.stream(attributes)
.forEach(a -> {
builder[0] = builder[0].attribute(a);
});
return builder.build();
Yuck.