I have some misunderstanding about Java 8 static method references.
The following is a correct statement:
Stream.of("aaa", "bbb", "cccc").map(String::length);
AFAIK map
requires a Function<T, R> interface
as an argument with method similar to:
R apply(T t);
However, the length()
method of String
class doesn't accept any arguments:
public int length() {
return value.length;
}
1) How does it correlate with apply
method which needs an argument T t
?
2) If I write String::someMethod
doesn't it mean that someMethod
should be static (since I'm calling it by class name, not by an object reference)?
Thank you!
No, String::someMethod
doesn't mean the method has to be static. It could be either a static method, or an instance method that would be executed on some String
instance. That instance would serve as an implicit argument of the single method of the functional interface implemented by that method reference.
Therefore String::length
does have a single argument - the String
instance on which the length
method will be called.
String::length
is equivalent to the lambda expression (String s) -> s.length()
(or just s -> s.length()
).
When you write Stream.of("aaa", "bbb", "cccc").map(String::length)
, the length()
method would be executed for each element of your Stream
(assuming you add some terminal operation that causes map
to be evaluated on these elements) which would transform your Stream<String>
to a Stream<Integer>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With