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?
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.
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) .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With