Java8 创建Stream的几种方法

  1. Stream的静态方法 of 可以将数组转换为Stream
    //Stream.of(T... values) 参数为一组数组
    String[] strings = { "java", "js", "angular", "react", "vue" };
    Stream<String> stream1 = Stream.of(strings);
    Stream<String> stream2= Stream.of("java", "js", "angular", "react", "vue");
  2. Arrays的静态方法 stream可以将数组【的一部分转换为stream //Arrays.stream(T[] array) array为一组数组String[] strings = { “java”, “js”, “angular”, “react”, “vue” };Stream<String> stream1 = Arrays.stream(strings);//Arrays.stream(T[] array, int startInclusive, int endExclusive);//array为一组数组,startInclusive为要截取的那部分数组的起始下标,endExclusive为要截取的那部分数组的结束下标+1Stream<String> stream2 = Arrays.stream(strings, 0, 3);//java,js,angular
  3. Stream的静态方法 empty 可以创建空的stream
    //Stream.empty() 无参数
    Stream<String> stream = Stream.empty();
    System.out.println(stream.count());//0
    
  4. Stream的的静态方法generate 可以产生一个特定的值的stream
    //Stream.generate(Supplier<T> s)  参数为Supplier函数接口,利用lambda表达式实现该接口,没有任何输入,返回T   
    Stream<String> stream = Stream.generate(() -> "java");
    stream .forEach(e -> System.out.println(e));//java
    
    
    原文作者:那些年的国文课
    原文地址: https://blog.csdn.net/u014519461/article/details/77592549
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞