Java-Stream重用流

** 1. 一个 Stream 只可以使用一次**
多次使用就会报错:stream has already been operated upon or closed,流已经被操作或关闭
** 2. 解决方法一**
利用Supplier接口重用流

package day12.prepareLesson.c_Stream;

import java.sql.SQLOutput;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class StreamFilter03 {
    public static void main(String[] args) {
        String[] arr = {"张无忌", "张三丰", "周芷若","张哈哈","张明"};
        
        //重用流
        Supplier<Stream<String>> supplier = ()->Stream.of(arr);
        /*
        使用过程中用Supplier接口的get方法获取对应的Stream对象【supplier.get()】,并对对象操作。
        */
        //第一次使用流
        supplier.get().forEach(x-> System.out.println(x));
		
		 //第二次使用流
        long count = supplier.get().filter(x->"张明".equals(x)).count();
        System.out.println("count = " + count);

		//第三次使用流
        Stream<String> res3 = supplier.get().limit(3);
        System.out.println("res3 = " + res3.count());

    }
}

3. 解决方法二


package day12.prepareLesson.c_Stream;

import java.sql.SQLOutput;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class StreamFilter03 {
    public static void main(String[] args) {
        String[] arr = {"张无忌", "张三丰", "周芷若","张哈哈","张明"};
        //第一次获取流对象
        Stream<String> original = Stream.of(arr);
        Stream<String> res = original.filter((String str)->{
            return str.startsWith("张");
        });
        System.out.println(res.count());
        
        //第二次获取流对象
        Stream<String> original2 = Stream.of(arr);
        //获取前几个元素,limit(long l);
        Stream<String> res2 = original2 .limit(2);
        System.out.println(res2.count())

    }
}

你可能感兴趣的:(Stream,stream,has,already,been,operated,up,Stream重用流,java)