Java 8 – Convert Iterator to Stream

There are 2 ways to convert an Iterator to Stream in Java 8 –

  • Use StreamSupport.stream to convert an Iterator into a Stream
  • Use StreamSupport.stream with Spliterator parameter

1. Iterator to Stream

The Iterator interface has no spliterator() method, so we need to use Spliterators.spliteratorUnknownSize to convert the Iterator into a Spliterator, followed by StreamSupport.stream to convert the Spliterator into a Stream.

package com.codehelp.java8;

import static java.util.stream.StreamSupport.stream;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;

public class IteratorToStream {
    public static void main(final String[] args) {

        final List items = new ArrayList<>();
        items.add("Alpha");
        items.add("Beta");
        items.add("Charlie");
        items.add("Delta");
        items.add("Echo");
        items.add("Foxtrot");

        final Iterator iterator = items.iterator();

        // Iterator -> Spliterators -> Stream -> List
        final List result = stream(
                Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
                .map(x -> x.length())
                .collect(Collectors.toList());

        result.forEach(x -> System.out.println(x));
        System.out.println(result.getClass());
        
    }
}

 

2. Iterator to Stream

Iterable interface has a spliterator() method and it is easier to convert it into a Stream.

package com.codehelp.java8;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class IteratorToStream {
    public static void main(final String[] args) {

        final Iterable iterable = Arrays.asList(1, 2, 3, 4, 5);

        // Iterable -> Spliterators -> Stream -> List
        final List result = StreamSupport
                .stream(
                iterable.spliterator(), false)
                .map(x -> x * 10)
                .collect(Collectors.toList());

        result.forEach(x -> System.out.println(x));
        System.out.println(result.getClass());
        
    }
}

Please Post Your Comments & Reviews

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.