Reputation: 1540
I want to get a stream into an immutable list. What is the difference between following approaches and which one is better from performance perspective?
collect( Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));
ImmutableList.copyOf( stream.iterator() );
collect( Collector.of(
ImmutableList.Builder<Path>::new,
ImmutableList.Builder<Path>::add,
(l, r) -> l.addAll(r.build()),
ImmutableList.Builder<Path>::build) );
A few more parameters for performance or efficiency,
There may be many entries in the list/collection.
What if I want the set sorted, using the intermediate operation ".sorted()"
with a custom comparator.
.parallel()
to the streamUpvotes: 6
Views: 1480
Reputation: 198014
I would expect 1) to be the most efficient: going via extra builders seems less readable and unlikely to win over normal toList()
, and copying from the iterator discards sizing information.
(But Guava is working on adding support for Java 8 things like this, which you might just wait for.)
Upvotes: 2
Reputation: 51501
For system performance, you need to measure it.
For programming performance, use the clearest way. From appearance alone, I like the second one best, and I see no obvious inefficiency there.
Upvotes: 3