Java – Convert Iterator to Stream

Use Spliterators.spliterator() or Spliterators.spliteratorUnknownSize() to convert an iterator to a stream

 

package com.pwn.stream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class IteratorToStream {

	public static void main(String[] args) {

		Iterator<String> iterator = Arrays.asList("A", "B", "C")
				.iterator();
		Spliterator<String> spliterator = Spliterators
				.spliteratorUnknownSize(iterator, 0);
		Stream<String> stream = StreamSupport.stream(spliterator,
				false);
		stream.forEach(System.out::println);

	}
}
A
B
C

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s