在Java中,是否有可能让一个lambda接受多种不同的类型?
即:
单变量有效:
Function <Integer, Integer> adder = i -> i + 1;
System.out.println (adder.apply (10));
可变参数也可以工作:
Function <Integer [], Integer> multiAdder = ints -> {
int sum = 0;
for (Integer i : ints) {
sum += i;
}
return sum;
};
//....
System.out.println ((multiAdder.apply (new Integer [] { 1, 2, 3, 4 })));
但我想要一些可以接受许多不同类型的参数,例如:
Function <String, Integer, Double, Person, String> myLambda = a , b, c, d-> {
[DO STUFF]
return "done stuff"
};
它的主要用途是在函数中加入小的内联函数以方便使用。
我已经环顾谷歌和检查Java的函数包,但不能找到。这可能吗?
在这种情况下,你可以使用默认库(java 1.8)中的接口:
java.util.function.BiConsumer
java.util.function.BiFunction
有一个小的(不是最好的)例子默认方法在接口:
default BiFunction<File, String, String> getFolderFileReader() {
return (directory, fileName) -> {
try {
return FileUtils.readFile(directory, fileName);
} catch (IOException e) {
LOG.error("Unable to read file {} in {}.", fileName, directory.getAbsolutePath(), e);
}
return "";
};
}}
我认为我们可以将map作为参数传递,并将不同的值作为map的元素传递。
Function <Map <String, Object>, Integer> multiAdder = i -> {
String param1 = (String)i.get("PARAM1");
Integer param2 = (Integer)i.get("PARAM2");
Double param3 = (Double)i.get("PARAM3");
Integer x = callAnotherMethod(param1, param2, param3);
return x;
};
//....
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("PARAM1", "String Val");
paramsMap.put("PARAM2", new Integer(12));
paramsMap.put("PARAM3", new Double(45);
System.out.println ((multiAdder.apply (paramsMap )));
在这种情况下,你可以使用默认库(java 1.8)中的接口:
java.util.function.BiConsumer
java.util.function.BiFunction
有一个小的(不是最好的)例子默认方法在接口:
default BiFunction<File, String, String> getFolderFileReader() {
return (directory, fileName) -> {
try {
return FileUtils.readFile(directory, fileName);
} catch (IOException e) {
LOG.error("Unable to read file {} in {}.", fileName, directory.getAbsolutePath(), e);
}
return "";
};
}}
对于有两个参数的东西,你可以使用biffunction。如果你需要更多,你可以定义自己的函数接口,如下所示:
@FunctionalInterface
public interface FourParameterFunction<T, U, V, W, R> {
public R apply(T t, U u, V v, W w);
}
如果有多个形参,你需要在参数列表周围加上圆括号,如下所示:
FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
// do something
return "done something";
};