在Java中,可以使用簡單的乘法操作符*
進行乘法運算,例如:
int a = 5;
int b = 10;
int result = a * b;
System.out.println(result); // 輸出50
而在Java 8中引入了Stream API,可以使用Stream的reduce
方法進行乘法操作。下面是一個使用Stream API進行乘法運算的示例:
List<Integer> numbers = Arrays.asList(2, 4, 6, 8);
int product = numbers.stream().reduce(1, (a, b) -> a * b);
System.out.println(product); // 輸出384
在上面的示例中,我們將一個整數列表中的所有元素相乘得到最終的乘積。reduce
方法接受一個初始值和一個BinaryOperator函數作為參數,將列表中的所有元素依次應用函數進行計算。