Java 8: Convert Iterator to Stream Examples


To Convert an Iterator to a Stream using Java 8 we can make use of the StreamSupport.stream() method from the java.util.stream package.

Example:
Iterator<String> iterator = collectionObject.iterator();

//Iterator to Stream
Stream<String> stream = StreamSupport.stream(
         Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);

Code Example:
package org.code2care.java.examples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class Java8IteratorToStream {

    public static void main(String[] args) {

        List<String> listOfCountries = new ArrayList<>();
        listOfCountries.add("USA");
        listOfCountries.add("Canada");
        listOfCountries.add("Australia");
        listOfCountries.add("China");
        listOfCountries.add("India");

        Iterator<String> iterator = listOfCountries.iterator();

        Stream<String> stream = StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);

        stream.forEach(System.out::println);
    }

}
Output:

USA
Canada
Australia
China
India

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap