JAVA - Stream - stream has already been operated upon or closed

原因

        Stream只能被消费一次,当其调用了终止操作后便说明其已被消费掉了。 如果还想重新使用,可考虑在原始数据中重新获得。

错误代码

public void test1(){
    List<Person> list = new ArrayList();
    list.add(new Person("妖姬", "女",19));
    list.add(new Person("张三", "男",19));
    list.add(new Person("李四", "男",20));
    list.add(new Person("王五", "男",20));
    list.add(new Person("赵六", "男",21));
    list.add(new Person("卡莎", "女",21));

    Stream<Person> stream = list.stream();
    List<Person> tempList1 = stream.filter(person -> person.getAge() > 20)
        .collect(Collectors.toList());
    System.out.println(tempList1);
    List<Person> tempList2 = stream.filter(person -> "女".equals(person.getGender()))
        .collect(Collectors.toList());
    System.out.println(tempList2);
}

        从日志中可以看出 tempList1是有被打印出来的,错误发生在获取tempList2的过程中。 而tempList2获取失败的原因就是在获取tempList1的时候调用了collect的方法,该方法为终止操作,执行完后就代表stream已经被消费了。

修改

public void test1(){
    List<Person> list = new ArrayList();
    list.add(new Person("妖姬", "女",19));
    list.add(new Person("张三", "男",19));
    list.add(new Person("李四", "男",20));
    list.add(new Person("王五", "男",20));
    list.add(new Person("赵六", "男",21));
    list.add(new Person("卡莎", "女",21));

    List<Person> tempList1 = list.stream().filter(person -> person.getAge() > 20)
        .collect(Collectors.toList());
    System.out.println(tempList1);
    List<Person> tempList2 = list.stream().filter(person ->"女".equals(person.getGender()))
        .collect(Collectors.toList());
    System.out.println(tempList2);
}

        改造后的代码,重新从原始数据中获取流就不会出现异常。


版权声明:本文为qq_34354257原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。