Method Parameters

Can I pass parameters using a method reference? For example, I have to create TreeMap, but using reverseOrder(). Is there something like TreeMap::new(reverseOrder())?

+4
source share
4 answers

No, you cannot do this with a method reference.

Instead, you can use lambda expressions:

() -> new TreeMap<TheRelevantType>(reverseOrder())

or

() -> new TreeMap<>(reverseOrder())

if you use this expression in a context where the compiler can infer the type of an element TreeMap.

+6
source

For this you need a lambda expression ... you are probably thinking about Supplier:

() -> new TreeMap<>(Comparator.reverseOrder())
+5
source

(), , Eclipse Collections API. :

Map<String, TreeSet<String>> jdkMap = new HashMap<>();
jdkMap.put("one", new TreeSet<>(Comparator.reverseOrder()));
jdkMap.computeIfAbsent("two", key -> new TreeSet<>(Comparator.reverseOrder()));

MutableMap<String, TreeSet<String>> ecMap =
        Maps.mutable.with("one", new TreeSet<>(Comparator.reverseOrder()));
ecMap.getIfAbsentPutWith("two", TreeSet::new, Comparator.<String>reverseOrder());

Assert.assertEquals(jdkMap, ecMap);

JDK Map.computeIfAbsent(), Function , Eclipse Collections 'MutableMap.getIfAbsentPutWith(), Function, . JDK . TreeSet::new Comparator.<String>reverseOrder() , .

*With, Eclipse (, selectWith, rejectWith, collectWith, detectWith, anySatisfyWith ..). , Java 8.

, Eclipse Collections Katas.

Kata → 2
Pet Kata → 2

. Eclipse.

+1

Java. :

Supplier<Map<String, String>> factory = () ->
        new TreeMap<>(Comparator.reverseOrder());

- / , :

public static <T, U> Supplier<T> withArg(
        Function<? super U, ? extends T> methodRef,
        U arg) {
    return () -> methodRef.apply(arg);
}

Supplier<Map<String, String>> factory = withArg(
        TreeMap::new, 
        Comparator.<String>reverseOrder());
+1
source

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


All Articles