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 streamIntroduced 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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With