Java Online Compiler
Example: SumArrayStreamReduce in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// SumArrayStreamReduce import java.util.Arrays; // Required for Arrays.stream() public class Main { public static void main(String[] args) { // Step 1: Define the array of numbers int[] numbers = {10, 20, 30, 40, 50}; // Step 2: Convert the int array to an IntStream and reduce it to a sum // The first argument (0) is the initial identity value for the sum. // The second argument (Integer::sum) is a method reference to the addition operation. int sum = Arrays.stream(numbers).reduce(0, Integer::sum); // Step 3: Print the calculated sum System.out.println("Sum using Stream.reduce() with method reference: " + sum); // Alternatively, using a lambda expression: int sumLambda = Arrays.stream(numbers).reduce(0, (a, b) -> a + b); System.out.println("Sum using Stream.reduce() with lambda: " + sumLambda); } }
Output
Clear
ADVERTISEMENTS