Convert Iterable to Stream using Java 8 JDK
Transform an Iterable
into a sequential Stream
using this snippet:
To obtain a parallel Stream
, tweak the second argument to true
:
This method utilizes spliterator, which offers the best of both worlds – performance and parallelism.
Direct Conversion for Collection Types
If your Iterable
is masquerading as a Collection, you can convert it directly using the stream()
function:
Most Collection
use stealthily efficient spliterators, potentially enhancing conversion speed.
Libraries: Guava and JOOQ’s Techniques
Guava Sneak Attack
Guava library (version 21.0 onwards) provides a ninja move for conversion:
JOOQ’s Secret Weapon
If you're a jOOQ ninja, the conversion is equally smooth:
These libraries aren't just bells and whistles. They add extra functionality and simplify syntax, aiding your stealth operations.
Custom Spliterator for Non-Collection Iterable
If your Iterable
isn't a disguise and truly isn't a Collection, a custom spliterator can give you a stealth advantage:
You define Spliterator characteristics which alter stream operations, especially crucial in parallel streams.
Taming Infinite Iterables
Working with gigantic or even infinite Iterable
datasets is like taming a dragon. Be cautious of your stream operations.
This technique prevents dragon-fire-esque destruction such as out of memory errors or infinite loops.
Stream API Operations on Iterable
Sometimes, don't change Iterable
to Stream
. Simply use Stream API operations directly:
Was this article helpful?