Java 8 – chaining constructor call and setter in stream.map()

If this happens repeatedly, you may create a generic utility method handling the problem of constructing an object given one property value:

public static <T,V> Function<V,T> create(
    Supplier<? extends T> constructor, BiConsumer<? super T, ? super V> setter) {
    return v -> {
        T t=constructor.get();
        setter.accept(t, v);
        return t;
    };
}

Then you may use it like:

List<Foo> l = Arrays.stream(fooString.split(","))
    .map(create(Foo::new, Foo::setName)).collect(Collectors.toList());

Note how this isn’t specific to Foo nor its setName method:

List<List<String>> l = Arrays.stream(fooString.split(","))
    .map(create(ArrayList<String>::new, List::add)).collect(Collectors.toList());

By the way, if fooString gets very large and/or may contain lots of elements (after splitting), it might be more efficient to use Pattern.compile(",").splitAsStream(fooString) instead of Arrays.stream(fooString.split(",")).

Leave a Comment