在Java中将Iterable转换为Stream
假设以下是我们的Iterable-
Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P");
现在,创建一个集合-
Stream<String> s = convertIterable(i);
上面,我们有一个自定义方法convertIterable()进行转换。以下是方法-
public static <T> Stream<T> convertIterable(Iterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); }
示例
以下是在Java中将Iterable转换为Stream的程序-
import java.util.*; import java.util.stream.*; public class Demo { public static <T> Stream<T> convertIterable(Iterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); } public static void main(String[] args) { Iterable<String> i = Arrays.asList("K", "L", "M", "N", "O", "P"); Stream<String> s = convertIterable(i); System.out.println("Iterable to Stream: "+s.collect(Collectors.toList())); } }
输出结果
Iterable to Stream: [K, L, M, N, O, P]