chiperortiz chiperortiz - 8 months ago 39
Java Question

Java 8 Pattern predicate using Stream how variable is infer?

Hi i am reading Java 8 for the real impatient and i see a code which gives me curiosity is like this

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

I just thought that asPredicate method would be something like

public boolean asPredicate(String stringToMatch){

But the real implementation is like this

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

Yes i know that i could use something like this and is perfectly legal

final long count = Stream.of("Cristian","Daniel","Ortiz","Cuellar")

But my question is how the stream somehow pass the String to Pattern instance? how "Cristian","Daniel","Ortiz","Cuellar" each are passed to the method s -> matcher(s).find(). I mean how the Strings are somehow passed and become the s variable of the asPredicate method.

Sorry if the question is somehow simple but this really gives me nightmares and sorry by my poor english.. Best Regards.


The Predicate interface is a functional interface that defines one abstract method boolean test(T t) where T in this case is the String type, since you're filtering on a Stream<String>. In other words, the code is equivalent to:

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