Creating general Lambdas with Java
•
Java
In Java, you can add a type parameter to a static method to create a method that handles generics Can you do the same thing with Lambdas?
In my code, I have
final private static <K,V> supplier<Map<K,List<V>> supplier=HashMap::new;
I'm trying to make type arguments, for example, it's a function, but it won't let me
If I do this:
final private static supplier<Map<?,List<?>>> supplier=HashMap::new;
It does not accept the argument that I try to use it What can I do?
Solution
One solution might be to wrap the method reference in the method so that the target type derivation resolves the type on the calling 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,List<V>> supplier=HashMap::new;
final private static supplier<Map<?,List<?>>> supplier=HashMap::new;
// A workaround
private static <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());
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
