【问题标题】:Stream filter method is not executed every time [duplicate]不是每次都执行流过滤方法[重复]
【发布时间】:2020-06-17 21:44:24
【问题描述】:
public class Test {


  public static void main(String[] args) {

    long filtered = Stream.of("test1", "test2", "test3")
        .filter(getPredicate())
        .count();
    System.out.println(filtered);

  }

  private static Predicate<String> getPredicate() {
    System.out.println("print this");//<-- this line was printed only once
    return item -> item.contains("test");
  }

}

我预计上面的代码会打印 3 次 打印这个。但它只打印了一次,谁能解释一下?

【问题讨论】:

  • 你的代码调用getPredicate()多少次?
  • 它被调用过一次

标签: java


【解决方案1】:

getPredicate()filter() 之前被调用,所以你看到“打印这个”一次。你返回的谓词被调用了 3 次,如果你想看到那个 try:

private static Predicate<String> getPredicate() {
   System.out.println("print this");
  return item -> {
       System.out.println("print that");
       return item.contains("test");
  };
}

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 2020-06-07
    • 2023-04-11
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    相关资源
    最近更新 更多