In this example, we will see “How to perform multiplication of two numbers in Java 8?”. To achieve that, we are going to use BiFunction interface introduced in Java 8 as part of the functional interfaces and we will see it through several different ways.
Perform multiplication in Java 8 using Functional Interface...!!! Share on X
Example 1. Java 8 code for multiplication of two integer numbers (hard-coded integers)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.util.function.BiFunction; /** * Java 8 program for the multiplication of two numbers * * @author D.V */ public class Calculate_Multiplication_Numbers_Java8_Example1 { public static void main(String[] args) { System.out.println("Multiplication of Two Numbers using BiFunction Interface - 'apply' example \n"); int number1 = 40; int number2 = 12; BiFunction < Integer, Integer, Integer > biFunctionObj = (i1, i2) - > (i1 * i2); System.out.println("Multiplication of 2 integer values - " + number1 + " and " + number2 + " is: " + biFunctionObj.apply(number1, number2)); } } |
Output:
1 2 3 | Multiplication of Two Numbers using BiFunction Interface - 'apply' example Multiplication of 2 integer values - 40 and 12 is: 480 |
Example 2. Java 8 code for multiplication of two integer numbers (scanner input)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.util.Scanner; import java.util.function.BiFunction; /** * Java 8 program for the multiplication of two numbers * * @author D.V */ public class Calculate_Multiplication_Numbers_Java8_Example2 { private static Scanner scanner; public static void main(String[] args) { System.out.println("Multiplication of Two Numbers using BiFunction Interface - 'apply' example \n"); scanner = new Scanner(System.in); System.out.println("\nEnter first number:"); int n1 = scanner.nextInt(); System.out.println("\nEnter second number:"); int n2 = scanner.nextInt(); BiFunction < Integer, Integer, Integer > biFunctionObj = (i1, i2) - > (i1 * i2); System.out.println("\nMultiplication of 2 integer values - " + n1 + " and " + n2 + " is: " + biFunctionObj.apply(n1, n2)); } } |
Output:
1 2 3 4 5 6 7 8 9 | Multiplication of Two Numbers using BiFunction Interface - 'apply' example Enter first number: 50 Enter second number: 9 Multiplication of 2 integer values - 50 and 9 is: 450 |
Perform multiplication in Java 8 using Functional Interface...!!! Share on X
Do you like this Post? – then check my other helpful posts: