1. Introduction
In this article, You'll be learning how to convert Iterable to Stream API.
Iterable is an interface in java and a method spliterator() is added to in Java 8 release.
2. Convert Iterable to Stream in Java 8
Since the Iterable interface has a spliterator() method and it is easier to convert it into a Stream.
Iterable to Stream in Java 8
Syntax:default Spliteratorspliterator()
Creates a Spliterator over the elements described by this Iterable.
First of all, Let us create a List and can assign to the iterable.
Iterable<String> iterable = Arrays.asList("Iterable", "to", "Stream", "in", "Java 8");
Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false);
3. Performing Stream Operations
Next, let us perform a simple Stream operation after converting Iterable to Stream with StreamSupport.stream() method.
package com.javaprogramto.java8.streams.iterable; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class IterableToStream { public static void main(String[] args) { Iterable<String> iterable = Arrays.asList("Iterable", "to", "Stream", "in", "Java 8"); Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false); List<String> list = stream.map(string -> string.toLowerCase()).collect(Collectors.toList()); list.forEach( value -> System.out.println(value)); } }
Output:
iterable to stream in java 8
4. Conclusion
In this article, You've seen how to convert Iterable of Strings into Stream of Strings using java 8 Stream API.
All the code is shown in this article is over GitHub.
You can download the project directly and can run in your local without any errors.
If you have any queries please post in the comment section.
No comments:
Post a Comment
Please do not add any spam links in the comments section.