Create a Sequential stream from an iterator in Java

Hello, Syntax Savants! In, this tutorial we are discussing the creation of a sequential stream from an iterator.

Iterators: Iterators are used in the Collection Framework to retrieve the elements one by one.

Stream: Stream in Java is used to produce the desired output from the sequence of objects that supports various methods.

Sequential stream from an iterator in Java

Spliterator: Spliterator is the same as other iterators, which is used for traversing the elements. The Iterator is first converted to Spliterator with the help of Spliterators.splieratorUnkownsize(). The Spliterator is then converted to Sequential Stream with the help of StreamSupport().stream function.

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class CodeSpeedy {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Apple", "Banana", "Cherry", "Mango", "Pineapple");
        Iterator<String> it = names.iterator();
        Stream<String> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), false);
        stream.map(String::toUpperCase).forEach(System.out::println);
    }
}

OUTPUT:

APPLE
BANANA
CHERRY
MANGO
PINEAPPLE

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top