Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we have 2 parameters in java.util.function.Function lambda?

We can create lambda functions like this:

Function<Integer, String> getLambda = (a) -> new String("given value is "a);

I have a scenario where I need to take 2 values in a parameter. How can I accomplish that using Function?

Example:

getLamda(10,20); // I know this line will give error. How can I acheive this? 
like image 402
Muneeb Nasir Avatar asked Sep 10 '15 14:09

Muneeb Nasir


People also ask

Can lambda have multiple parameters Java?

The lambda expressions are easy and contain three parts like parameters (method arguments), arrow operator (->) and expressions (method body). The lambda expressions can be categorized into three types: no parameter lambda expressions, single parameter lambda expressions and multiple parameters lambda expressions.

How many parameters can a lambda have?

A lambda function can have any number of parameters, but the function body can only contain one expression. Moreover, a lambda is written in a single line of code and can also be invoked immediately.

How do you pass two parameters in 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.


2 Answers

This is done using a BiFunction<T,U,R>. Following is an example of a BiFunction returning the character at the specified index of a String:

BiFunction<String, Integer, Character> charAtFunction = (string, index) -> string.charAt(index);
like image 85
Tunaki Avatar answered Oct 18 '22 02:10

Tunaki


Try :

BiFunction<Integer, Integer, String> lambda = (a, b) -> ("Given values are " + a + ", " + b);
like image 31
dotvav Avatar answered Oct 18 '22 01:10

dotvav