Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function.Function of Java 8 with multiple parameters [duplicate]

I read many examples about how to easily define a lambda in Java 8. This lambda takes always one parameter like f1:

Function<Integer,Integer> f1 = (x) -> Math.pow(x,2);

Of course, you can extend the body like f2:

Function<Integer,Integer> f2 = (x) -> {if (x < 0)  return 0;
                                       else return Math.pow(x,2);};

But I cannot find a way to define a lambda with a variable number of paramters like f3:

Function<Integer,Integer,Integer> f3 = (x,y) -> {return x + y};

or without parameter like f4:

Function<Double> f4 = () -> {return Math.random()};

I am almost sure that you can define own functional interface (i.e., create a new file commonly) to develop f3 and f4, but Is there some way to easily define them?

like image 893
Naive Developer Avatar asked Aug 09 '18 19:08

Naive Developer


People also ask

Can a method have multiple parameters Java?

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

What is the use of BiFunction in Java 8?

Interface BiFunction<T,U,R>Represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function . This is a functional interface whose functional method is apply(Object, Object) .

What is function identity () in Java 8?

identity. static <T> Function<T,T> identity() Returns a function that always returns its input argument. Type Parameters: T - the type of the input and output objects to the function Returns: a function that always returns its input argument.


1 Answers

Function<Integer,Integer,Integer> f3 = (x,y) -> {return x + y};

is actually a BiFunction<Integer,Integer,Integer>

and

Function<Double> f4 = () -> {return Math.random()};

is a Supplier<Double>

If you need more create your own, like TriFunction<Integer,Integer,Integer,Integer> for example

like image 157
Eugene Avatar answered Oct 05 '22 11:10

Eugene