Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 259
ameet chaubal Avatar asked Nov 11 '14 20:11

ameet chaubal


People also ask

What would be a good way to describe stream in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

How do you collect stream strings?

We can use Collectors joining() methods to get a Collector that concatenates the input stream CharSequence elements in the encounter order. We can use this to concatenate a stream of strings, StringBuffer, or StringBuilder.


2 Answers

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.

like image 109
Svante Avatar answered Sep 22 '22 01:09

Svante


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

like image 36
Louis Wasserman Avatar answered Sep 20 '22 01:09

Louis Wasserman