java lambda可以有多个参数吗?

Leo*_*sev 140 java lambda java-8

在Java中,是否可以让lambda接受多种不同的类型?

即:单变量工作:

    Function <Integer, Integer> adder = i -> i + 1;
    System.out.println (adder.apply (10));
Run Code Online (Sandbox Code Playgroud)

Varargs也有效:

    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 })));
Run Code Online (Sandbox Code Playgroud)

但是我想要一些可以接受许多不同类型参数的东西,例如:

    Function <String, Integer, Double, Person, String> myLambda = a , b, c, d->  {
    [DO STUFF]
    return "done stuff"
    };
Run Code Online (Sandbox Code Playgroud)

主要用途是在函数内部使用小内联函数以方便使用.

我查看了谷歌并检查了Java的功能包,但找不到.这可能吗?

Sot*_*lis 157

如果您使用多个类型参数定义这样的功能接口,则可能.没有这种内置类型.(有一些有限的类型有多个参数.)

@FunctionalInterface
interface Function<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}
Run Code Online (Sandbox Code Playgroud)

如果这就是您所询问的,那么也无法定义可变数量的类型参数.


某些语言(如Scala)定义了许多内置的类型,包括1,2,3,4,5,6等类型参数.

  • 你可以随时使用Currying:`Function <One,Function <Two,Function <Three,Function <Four,Function <Five,Six >>>>> func = a - > b - > c - > d - > e - > 'Z';` (47认同)
  • 柯里化?哇,这比函数式界面差多了。 (2认同)

tbo*_*odt 30

对于具有2个参数的东西,您可以使用BiFunction.如果您需要更多,可以定义自己的功能界面,如下所示:

@FunctionalInterface
public interface FourParameterFunction<T, U, V, W, R> {
    public R apply(T t, U u, V v, W w);
}
Run Code Online (Sandbox Code Playgroud)

如果有多个参数,则需要在参数列表周围加上括号,如下所示:

FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
    // do something
    return "done something";
};
Run Code Online (Sandbox Code Playgroud)


ayu*_*huk 26

对于这种情况,您可以使用默认库(java 1.8)中的接口:

java.util.function.BiConsumer
java.util.function.BiFunction
Run Code Online (Sandbox Code Playgroud)

接口中有一个小的(不是最好的)默认方法示例:

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 "";
    };
}}
Run Code Online (Sandbox Code Playgroud)

  • 如果您修改问题以说明如何使用这些接口来满足要求,您将从Java8粉丝获得更多的投票. (4认同)
  • BiFunction允许您仅定义两个参数的函数,问题是关于具有任意数量的参数的函数 (3认同)

小智 5

要使用lambda:共有三种类型的操作:
1.接受参数->使用者
2.测试参数返回布尔值->谓词
3.操作参数和返回值->函数

Java Functional接口,最多两个参数:
单参数接口
Consumer
Predicate
Function

两个参数接口
BiConsumer
BiPredicate
BiFunction

对于两个以上的对象,您必须创建如下的功能接口(消费者类型):

@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
    public void accept(T t, U u, V v, W w, X x);
}
Run Code Online (Sandbox Code Playgroud)