conjure-java icon indicating copy to clipboard operation
conjure-java copied to clipboard

Accept Stream<T> in collection-like builder fields

Open henryptung opened this issue 6 years ago • 3 comments

Since Conjure always makes a defensive copy and the element type may need conversion, accepting only Iterable<T> encourages creation of a "waste" copy:

Bean bean = Bean.builder()
        .values(myValues.stream().map(Converter::convert).collect(toList()))
        .build();

Instead, this could accept the stream directly, use .forEachOrdered and avoid the extra copy:

Bean bean = Bean.builder()
        .values(myValues.stream().map(Converter::convert))
        .build();

henryptung avatar Aug 23 '19 23:08 henryptung

This can be done much more efficiently using Lists.transform which avoids stream overhead, and allows the conjure builder to presize the internal collection.

Bean bean = Bean.builder()
        .values(Lists.transform(myValues, Converter::convert))
        .build();

The following also works, but not in a fluent way:

Bean.Builder builder = Bean.builder();
myValues.stream().map(Converter::convert).forEach(builder::values));
Bean bean = builder.build();

carterkozak avatar Aug 23 '19 23:08 carterkozak

@carterkozak Does Collections2.transform yield the same presizing benefits?

henryptung avatar Aug 24 '19 01:08 henryptung

It does

carterkozak avatar Aug 24 '19 01:08 carterkozak