ameet chaubal
ameet chaubal

Reputation: 1540

The best way to collect the Java-8 Stream to Guava ImmutableList

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?

  1. collect( Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));

  2. ImmutableList.copyOf( stream.iterator() );

  3. 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,

  1. There may be many entries in the list/collection.

  2. What if I want the set sorted, using the intermediate operation ".sorted()" with a custom comparator.

  3. consequently, what if I add .parallel() to the stream

Upvotes: 6

Views: 1480

Answers (2)

Louis Wasserman
Louis Wasserman

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

Svante
Svante

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

Related Questions