-2
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");
  }

}

I expected the above code to 3 times print out print this. But it printed only once, can someone explain?

Siva
  • 3
  • 2

1 Answers1

2

getPredicate() is called before filter() so you see "print this" once. The predicate you return is called three times, if you wanted to see that try:

private static Predicate<String> getPredicate() {
   System.out.println("print this");
  return item -> {
       System.out.println("print that");
       return item.contains("test");
  };
}
Bashir
  • 2,057
  • 5
  • 19
  • 44
DuncG
  • 12,137
  • 2
  • 21
  • 33