Java流中的中间操作

在 java 8 中,我使用 Streams 打印输出,但大小为 0。为什么?


public class IntermediateryAndFinal {

    public static void main(String[] args) {

        Stream<String> stream = Stream.of("one", "two", "three", "four", "five");


        Predicate<String> p1 = Predicate.isEqual("two");

        Predicate<String> p2 = Predicate.isEqual("three");


        List<String> list = new ArrayList<>();


        stream.peek(System.out::println)

            .filter(p1.or(p2))

            .peek(list::add);

        System.out.println("Size = "+list.size());

    }

}


鸿蒙传说
浏览 110回答 4
4回答

慕哥9229398

理想情况下,您不应该改变外部列表,而是可以使用Collectors.toList()将其收集到列表中:List<String> list = stream.peek(System.out::println)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(p1.or(p2))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList()); // triggers the evaluation of the streamSystem.out.println("Size = "+list.size());在您的示例中,仅当终端操作像allMatch()anyMatch()&nbsp;noneMatch()&nbsp;collect()&nbsp;count()&nbsp;forEach()&nbsp;min()&nbsp;max()&nbsp;reduce()

料青山看我应如是

由于您还没有完成流操作,即peek是一个中间操作。您必须使用终端操作才能继续执行。建议:改为使用终端操作执行此类操作,例如collectList<String> list = stream.peek(System.out::println)&nbsp; &nbsp; &nbsp; &nbsp; .filter(p1.or(p2))&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());另外:添加一个peek帖子filter来观察值在观察中可能有点棘手,如下代码List<String> list = stream.peek(System.out::println)&nbsp; &nbsp; &nbsp; &nbsp; .filter(p1.or(p2))&nbsp; &nbsp; &nbsp; &nbsp; .peek(System.out::println) // addition&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());输出看起来像:onetwotwo // filtered inthreethree // filtered infourfive

温温酱

溪流是懒惰的。您可以调用终端操作,例如forEach:stream.peek(System.out::println) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(p1.or(p2)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.forEach(list::add);如果您想peek用作调试目的的中间操作,那么您必须在之后调用终端操作:stream.peek(System.out::println) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(p1.or(p2)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.peek(list::add); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.<any&nbsp;terminal&nbsp;operation&nbsp;here>();顺便说一句,如果您只想将所有过滤后的值存储在一个列表中,那么最好使用collect(toList()).

冉冉说

您所做的一切filter都是peek设置一系列操作以应用于流。您实际上还没有使它们中的任何一个运行。您必须添加一个终端操作,例如count.&nbsp;(另一个答案建议使用forEach添加到列表中,但我认为您专门尝试使用中间操作peek。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java