Sunday 5 January 2020

Convert Stream to Iterable


‘stream::iterator’ return Iterable from Stream.

public static <T> Iterable<T> getIterable(Stream<T> stream){
         return stream::iterator;
}

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

public class App {

	public static <T> Iterable<T> getIterable(Stream<T> stream) {
		return stream::iterator;
	}

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

		Stream<Integer> stream = primes.stream();

		Iterable<Integer> iterable = getIterable(stream);

		Iterator<Integer> iterator = iterable.iterator();

		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}

}

Output
2
3
5
7
11




You may like

No comments:

Post a Comment