6

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
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
ameet chaubal
  • 1,440
  • 16
  • 37
  • Related: [How can I collect a Java 8 stream into a Guava ImmutableCollection?](https://stackoverflow.com/questions/29013250/how-can-i-collect-a-java-8-stream-into-a-guava-immutablecollection) – Jeffrey Bosboom Dec 15 '15 at 23:10

2 Answers2

3

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.

Svante
  • 50,694
  • 11
  • 78
  • 122
2

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.)

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • thanks, could you please elaborate "copying from the iterator discards sizing information" – ameet chaubal Nov 12 '14 at 18:04
  • A `Stream.iterator()` doesn't know its size. Going via `toList()` gets you a sized list. It could be argued either way, though -- you're losing the sizing information when you build the `List`, but you have it back when you copy it to the `ImmutableList`. – Louis Wasserman Nov 12 '14 at 19:56