Functional Interface as a Function

public static void main(String o[]) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("a", 1);
    map.entrySet().stream().sorted(Comparator.comparing(Entry::getValue)).forEach(System.out::println);
}

The above code builds and works fine, but it shouldn't. Comparator.comparing accepts a reference to a function, and only those methods that take one argument and return one argument can be matched with this. But in the above code, getValue is displayed and working fine, but does not accept any parameters. The code should give a build question, but it doesn't. Is there a problem with my concept?

+4
source share
2 answers

Single argument method comparing:

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor)

Function<? super T, ? extends U>, , , .

Entry::getValue (Map.Entry<String, Integer> ) (Integer ). Function.

getValue , .

, - Map.Entry, Stream, apply() Function.

, :

Function<Map.Entry<Integer, String>, String> func = Map.Entry::getValue;

getValue() Map.Entry Function, Map.Entry ( getValue() ).

+5

- , , , :

Entry.getValue(item)

item.getValue() [JavaDoc] (https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html#getValue())

: p -> p.getValue(), , , Function<Entry<String, Integer>, Integer>.

, , :

+2

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


All Articles