Java Online Compiler
Example: Sum of Array Elements using Java 8 Stream API (reduce()) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Array Elements using Java 8 Stream API (reduce()) import java.util.Arrays; // Required for Arrays.stream() import java.util.OptionalInt; // For the result of reduce() // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Define the array of integers int[] numbers = {10, 20, 30, 40, 50}; // Step 2: Convert the array to an IntStream and apply the reduce operation // reduce(identity, accumulator) // identity: The initial value of the reduction, and the default result if the stream is empty. // accumulator: A BiFunction that takes two arguments and returns one. int sum = Arrays.stream(numbers).reduce(0, (a, b) -> a + b); // Step 3: Print the calculated sum System.out.println("Sum of array elements (Stream API reduce()): " + sum); // Alternative with OptionalInt for empty streams (if no identity is provided) OptionalInt optionalSum = Arrays.stream(numbers).reduce(Integer::sum); if (optionalSum.isPresent()) { System.out.println("Sum with reduce (OptionalInt): " + optionalSum.getAsInt()); } else { System.out.println("Stream was empty (OptionalInt)."); } } }
Output
Clear
ADVERTISEMENTS