In: Computer Science
Design a Java program named LambdaTester2 which includes a main method that declares a lambda expression reference which implements the following interface:
interface Multiplier
{
int
multiply(int
num1, int num2);
}
The program must declare an array of Pair objects (see class specification below), followed by the declaration of an ArrayList which is instantiated using the declared array (the ArrayList stores Pair objects).
Then write a loop which iterates through each element of the ArrayList, calls the lambda expression reference with the element fields as arguments and displays the resulting multiplied value.
The Pair class is implemented as follows, include it with default (not public) visibility in the same source file as your LambdaTester2 class.
class Pair { private int num1, num2; public Pair() {} public Pair(int num1, int num2) { this.num1 = num1; this.num2 = num2; } public int getNum1() { return num1; } public int getNum2() { return num2; } }
Sample output follows for a Pair array declared as
Pair[] pArray = { new Pair(2, 4), new Pair(3, 6), new Pair(4, 7) };
Remember that your multiplied values must come from an ArrayList created from an array similar to the one shown above.
Multiply 2 * 4 = 8
Multiply 3 * 6 = 18
Multiply 4 * 7 = 28
Explanation: I have written the lambda expression in the main method of the LambdaTester2 class,I have also instantiated the ArrayList with the given array of three Pair objects.I have used the for each loop to iterate over the ArrayList and call the multiply() method from the lambda expression from each object. I have also shown the output of the program, please find it attached with the answer.Please upvote if you liked my answer and comment of you need any explanation or modification.
//code starts
//Multiplier interface
public interface Multiplier {
int multiply(int num1, int num2);
}
//Pair class
class Pair {
private int num1, num2;
public Pair() {
}
public Pair(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public int getNum1() {
return num1;
}
public int getNum2() {
return num2;
}
}
//LambdaTester2 class
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class LambdaTester2 {
public static void main(String[] args) {
// lambda expression
Multiplier multiplier = (num1,
num2) -> {
return num1 *
num2;
};
// array declaration
Pair[] pArray = { new Pair(2, 4),
new Pair(3, 6), new Pair(4, 7) };
// declaration of an ArrayList
which is instantiated using the declared array
List<Pair> pairs = new
ArrayList<>();
pairs =
Arrays.asList(pArray);
for (Pair pair : pairs) {
System.out.println("Multiply " + pair.getNum1() + " * " +
pair.getNum2() + " = "
+
multiplier.multiply(pair.getNum1(), pair.getNum2()));
}
}
}
Output: