代码之家  ›  专栏  ›  技术社区  ›  PAA

Java流中的中间操作[复制]

  •  2
  • PAA  · 技术社区  · 6 年前

    这个问题已经有了答案:

    在Java 8中,我使用流打印输出,但是大小为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());
        }
    }
    
    4 回复  |  直到 6 年前
        1
  •  5
  •   Naman    6 年前

    理想情况下,您不应该改变外部列表,而是可以使用 Collectors.toList() 要将其收集到列表中,请执行以下操作:

    List<String> list = stream.peek(System.out::println)
                .filter(p1.or(p2))
                .collect(Collectors.toList()); // triggers the evaluation of the stream
    System.out.println("Size = "+list.size());
    

    在你的例子中, 只有在终端操作时才计算流 喜欢

    allMatch()
    anyMatch() 
    noneMatch() 
    collect() 
    count() 
    forEach() 
    min() 
    max() 
    reduce()
    

    遇到。

        2
  •  4
  •   Naman    6 年前

    因为您还没有完成流操作,即 peek 是一个中间操作。必须使用 终端操作 为了让这件事仍能执行。

    建议 :相反,使用终端操作执行此类操作,例如 collect

    List<String> list = stream.peek(System.out::println)
            .filter(p1.or(p2))
            .collect(Collectors.toList());
    

    另外:添加 偷看 邮递 filter 观察这些值在观察中可能有点困难,如下面的代码

    List<String> list = stream.peek(System.out::println)
            .filter(p1.or(p2))
            .peek(System.out::println) // addition
            .collect(Collectors.toList());
    

    输出如下:

    one
    two
    two // filtered in
    three
    three // filtered in
    four
    five
    
        3
  •  1
  •   ETO    6 年前

    小溪很懒。你必须像 forEach :

    stream.peek(System.out::println)
          .filter(p1.or(p2))
          .forEach(list::add);
    

    万一你想用 peek 作为调试的中间操作,之后必须调用终端操作:

    stream.peek(System.out::println)
          .filter(p1.or(p2))
          .peek(list::add);
          .<any terminal operation here>();
    

    顺便说一句,如果您只想将所有过滤后的值存储在一个列表中,那么最好使用 collect(toList()) .

        4
  •  0
  •   Willis Blackburn    6 年前

    你所做的一切 filter peek 设置应用于流的操作链。实际上你还没有让他们跑过。您必须添加终端操作,例如 count . (另一个答案建议使用 forEach 要添加到列表中,但我认为您正在特别尝试使用中间操作 偷看 )