Creating shared lambs in Java

In java, you can add type parameters to static methods to create methods that handle generics. Can you do the same with lambdas?

In my code I have

final private static <K,V> Supplier<Map<K, List<V>> supplier=HashMap::new; 

I am trying to use type parameters such as a function, but that will not allow me.

And if I do this:

  final private static Supplier<Map<?, List<?>>> supplier=HashMap::new; 

It does not accept the argument in which I am trying to use it. What can I do?

+6
source share
1 answer

A workaround for this may be to associate the method reference with the method, so that the output of the target type allows the type on the call site:

 import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; public class GenericLambda { // Syntactically invalid //final private static <K,V> Supplier<Map<K, List<V>> supplier=HashMap::new; final private static Supplier<Map<?, List<?>>> supplier=HashMap::new; // A workaround private static <K,V> Supplier<Map<K, List<V>>> supplier() { return HashMap::new; } public static void main(String[] args) { // Does not work //useSupplier(supplier); // Works useSupplier(supplier()); } private static <K, V> void useSupplier(Supplier<Map<K, List<V>>> s) { System.out.println(s.get()); } } 
+8
source

All Articles