Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream API map argument

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!

like image 425
SergeiK Avatar asked Jan 02 '23 12:01

SergeiK


1 Answers

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>.

like image 146
Eran Avatar answered Jan 15 '23 13:01

Eran