Java 8 – How to Convert Iterator to Stream

Introduction

In Java, an Iterator is commonly used to traverse collections, but Java 8's Stream API offers more powerful ways to process data using functional programming techniques. Converting an Iterator into a Stream allows you to apply various operations like filtering, mapping, and collecting on the collection's data.

Solution Steps

  1. Define an Iterator: Create an Iterator from a collection, such as a List.
  2. Convert the Iterator to a Stream: Use the StreamSupport.stream() method along with Spliterators.spliteratorUnknownSize() to convert the Iterator to a Stream.
  3. Process the Stream: Use Stream methods such as filter, map, and forEach to perform operations on the elements.
  4. Display the Result: Print the processed Stream data.

Java Program

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 IteratorToStreamExample {
    public static void main(String[] args) {
        // Step 1: Define a list and create an Iterator
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
        Iterator<Integer> iterator = numbers.iterator();

        // Step 2: Convert the Iterator to a Stream
        Stream<Integer> stream = StreamSupport.stream(
            Spliterators.spliteratorUnknownSize(iterator, 0), false);

        // Step 3: Process the Stream (filter even numbers and multiply by 2)
        stream.filter(num -> num % 2 == 0)   // Filter even numbers
              .map(num -> num * 2)           // Multiply even numbers by 2
              .forEach(System.out::println); // Display the result
    }
}

Output

4
8
12

Explanation

Step 1: Create an Iterator

We begin by defining a list of integers:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Iterator<Integer> iterator = numbers.iterator();

This step creates an Iterator from the list, which we will convert to a Stream.

Step 2: Convert the Iterator to a Stream

Next, we use StreamSupport.stream() along with Spliterators.spliteratorUnknownSize() to convert the Iterator into a Stream:

Stream<Integer> stream = StreamSupport.stream(
    Spliterators.spliteratorUnknownSize(iterator, 0), false);
  • Spliterators.spliteratorUnknownSize(iterator, 0): This creates a Spliterator from the given Iterator, which handles the iteration.
  • StreamSupport.stream(): This converts the Spliterator into a Stream. The second parameter (false) indicates that we do not want a parallel stream.

Step 3: Process the Stream

Once the Iterator is converted to a Stream, we can process it using Stream API methods:

stream.filter(num -> num % 2 == 0)   // Filter even numbers
      .map(num -> num * 2)           // Multiply even numbers by 2
      .forEach(System.out::println);  // Print the result
  • filter(num -> num % 2 == 0): This filters the stream, keeping only the even numbers.
  • map(num -> num * 2): This multiplies each filtered number by 2.
  • forEach(System.out::println): This prints each element of the resulting stream.

Step 4: Display the Result

The result is printed to the console, showing the processed even numbers after being multiplied by 2.

Conclusion

Using Java 8, converting an Iterator to a Stream is straightforward with the StreamSupport and Spliterator utilities. Once converted, the Stream API allows you to easily process the data using methods like filter, map, and forEach, providing a more powerful and flexible way to handle data compared to traditional loops.

Comments