Java Stream API Map Argument

I have some misunderstandings about Java 8 static method references.

This is the correct statement:

Stream.of("aaa", "bbb", "cccc").map(String::length);

An AFAIK map needs as Function<T, R> interfacean argument with a method similar to:

R apply(T t);

But the length()class method Stringtakes no arguments:

public int length() {
    return value.length;
}

1) How does this relate to a method applythat needs an argument T t?

2) If I write String::someMethod, does this mean that it someMethodshould be static? Because I call it the name of the class, not the object.

Thank!

+4
source share
2 answers

, String::someMethod , . , , String. , .

, String::length - String, length.

String::length - (String s) -> s.length() ( s -> s.length()).

Stream.of("aaa", "bbb", "cccc").map(String::length), length() Stream ( , , map ), Stream<String> a Stream<Integer>.

+6

lamdas/method , . - , .

Stream.of("aaa", "bbb", "cccc").map(new Function<String, Integer>() {
      @Override
      public Integer apply(String s) {
        return s.length();
      }
    }); 

, String, , Integer. Function functionalInterface, .

+3

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


All Articles