Problem:
How can I manipulate an Iterable using the Java 8 Stream API without converting it to a List?
Solution:
tl;dr: Use StreamSupport.stream(iterable.spliterator(), false) to create a stream from the iterable.
Detailed Explanation:
Iterable provides a spliterator() method that returns a Spliterator, which can be used to create a stream using StreamSupport.stream. Here's the code snippet:
StreamSupport.stream(iterable.spliterator(), false) .filter(...) .moreStreamOps(...);
This approach avoids unnecessary conversion to a List, which can improve performance and memory consumption. StreamSupport.stream takes two arguments:
The resulting stream can then be manipulated using Stream API operations like filter, map, etc.
Benefits:
Using StreamSupport.stream provides the following benefits:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3