Java 8中如何将Iterable转换为Stream呢?

书欣 Java经验 发布时间:2023-07-10 17:11:22 阅读数:13340 1
下文笔者讲述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));
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202307/16889803097049.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者