Can anyone tell me how this works:
long count = list.stream().filter(String::isEmpty).count();
The method String.isEmpty()
does not accept any parameters. How was it able to gain access to the elements of the Stream
in order for it to check if the elements are empty or not?
I saw a code where a method can have access to elements of the Stream
. I suppose it has access because the elements were passed as a parameter like below:
boolean isReal = list.stream().anyMatch(u -> User.isRealUser(u));
which essetnially the same as
boolean isReal = list.stream().anyMatch(User::isRealUser);
But String.isEmpty()
? It does not accept any parameters, how was it able to know the Stream
elements?
Update:
Below helped me in understanding what happened.
String::toLowerCase
is an unbound non-static method reference that identifies the non-static String toLowerCase()
method of the String
class.
However, because a non-static method still requires a receiver object (in this example a String
object, which is used to invoke toLowerCase()
via the method reference), the receiver object is created by the virtual machine. toLowerCase()
will be invoked on this object.
String::toLowerCase
specifies a method that takes a single String
argument, which is the receiver object, and returns a String
result.
String::toLowerCase()
is equivalent to lambda (String s) -> { return s.toLowerCase(); }
.
The last line above is what I was looking for. Given the lambda equivalent of String.toLowerCase()
, the elements of the Stream
are passed as variable s
to which toLowerCase()
is applied.