Java 8 – chaining constructor call and setter in

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 =","))
    .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 =","))
    .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",")).

Leave a Comment