Java 8 template predicate using Stream - how to output a variable?

I read “Java SE 8 for the really impatient,” and I see some kind of curious code. This is something like this:

final Pattern pattern = Pattern.compile(".....");
final long count = Stream.of("Cristian","Daniel","Ortiz","Cuellar")
      .filter(pattern.asPredicate())
      .count();

I just thought the asPredicate method would look like

public boolean asPredicate(String stringToMatch){
    .....
}

But the real implementation is like this

public Predicate<String>asPredicate(){
    return s -> matcher(s).find();
}

I know that I could use something like this that is completely legal:

final long count = Stream.of("Cristian","Daniel","Ortiz","Cuellar")
      .filter(a->pattern.matcher(a).find())
      .count();

But my question is, how does the stream pass the String to the Pattern instance? like “Christian”, “Daniel”, “Ortiz”, “Cuellar” each is transferred to the method s -> matcher(s).find(). I mean, how strings are somehow passed and become a variable of sthe asPredicate method.

+4
1

Predicate - , boolean test(T t), T String, Stream<String>. , :

final long count = Stream.of("Cristian","Daniel","Ortiz","Cuellar")
  .filter(new Predicate<String>() {
       public boolean test(String s) {
          return matcher(s).find();
       }
   })
  .count();
+4

Source: https://habr.com/ru/post/1655486/


All Articles