Wednesday, 3 May 2023

Get the stream from an iterator in Java

Using StreamSupport# stream method, we can get a new sequential or parallel Stream.

 

Step 1: Get the spliterator from iterator.

 

'Spliterators.spliterator' method return a spliterator from an Iterator.

 

public static <T> Spliterator<T> spliterator(Iterator<? extends T> iterator, long size, int characteristics)

public static <T> Spliterator<T> spliteratorUnknownSize(Iterator<? extends T> iterator, int characteristics)

Creates a Spliterator using a given Iterator as the source of elements, and with a given initially reported size.

 

Example 

Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);

 Step 2: Use StreamSupport.stream method to get the stream from a spliterator.

 

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel)

Creates a new sequential or parallel Stream from a Spliterator. If the argument 'parallel' is set to true then the returned stream is a parallel stream. If the argument 'parallel' is set to false then the returned stream is a sequential stream.

 

Example

StreamSupport.stream(spliterator, false);

Find the below working application.

 

Below snippet gets the Stream from an Iterator.

public static <T> Stream<T> toStream(final Iterator<T> iterator) {
	Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);
	return StreamSupport.stream(spliterator, false);
}

Find the below working application.


StreamFromIterator.java

package com.sample.app.streams;

import java.util.Arrays;
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 StreamFromIterator {

	public static <T> Stream<T> toStream(final Iterator<T> iterator) {
		Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);
		return StreamSupport.stream(spliterator, false);
	}

	public static void main(String[] args) {
		List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11);

		System.out.println("First 5 prime numbers : ");
		toStream(primes.iterator()).forEach(System.out::println);
	}
	
}

Output

First 5 prime numbers : 
2
3
5
7
11



You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an Iterable to a Set in Java

Get the last element from a collection in Java

Implement stack data structure using List

Get a composite unmodifiable array list from two arrays

Join the collection elements by a separator using streams

No comments:

Post a Comment