java lambda可以有多个参数吗? [英] Can a java lambda have more than 1 parameter?

查看:229
本文介绍了java lambda可以有多个参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java, is it possible to have a lambda accept multiple different types?

即:
单变量有效:

I.e: Single variable works:

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

Varargs也有效:

Varargs also work:

    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 })));

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

But I want something that can accept many different types of arguments, e.g:

    Function <String, Integer, Double, Person, String> myLambda = a , b, c, d->  {
    [DO STUFF]
    return "done stuff"
    };

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

The main use is to have small inline functions inside functions for convenience.

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

I've looked around google and inspected Java's Function Package, but could not find. Is this possible?

推荐答案

如果您定义具有多个类型参数的功能接口,则可以。没有这种内置类型。 (有一些带有多个参数的有限类型。)

It's possible if you define such a functional interface with multiple type parameters. There is no such built in type. (There are a few limited types with multiple parameters.)

@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';
}






也没办法定义一个可变数量的类型参数,如果这是你要问的。


There's also no way to define a variable number of type parameters, if that's what you were asking about.

某些语言,如Scala,定义了内置此类型的数量,具有1,2,3,4,5,6等类型参数。

Some languages, like Scala, define a number of built in such types, with 1, 2, 3, 4, 5, 6, etc. type parameters.

这篇关于java lambda可以有多个参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆