Java 8中如何将Iterable转换为Stream呢?
下文笔者讲述Iterable转换为Stream的方法及示例分享,如下所示
Iterable转换为Stream的方法
使用 1.获取可迭代对象。 2.使用 Iterable.spliterator()方法 将Iterable 转换为 Spliterator 3.使用 StreamSupport.stream()方法 将形成的 Spliterator 转换为 Sequential Stream 4.返回流例:Iterable转Stream
import java.util.*; import java.util.stream.*; class TestClass { // Function to get the Stream public static <T> Stream<T> getStreamFromIterable(Iterable<T> iterable) { // Convert the Iterable to Spliterator Spliterator<T> spliterator = iterable.spliterator(); // Get a Sequential Stream from spliterator return StreamSupport.stream(spliterator, false); } // Driver code public static void main(String[] args) { // Get the Iterator Iterable<Integer> iterable = Arrays.aslist(88,99,110,120); // Get the Stream from the Iterable Stream<Integer> stream = getStreamFromIterable(iterable); // Print the elements of stream stream.forEach(s -> System.out.println(s)); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。