Java Online Compiler
Example: Sum of Squares using Java 8 Streams (map and reduce) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Squares using Java 8 Streams (map and reduce) import java.util.Arrays; public class Main { public static void main(String[] args) { // Step 1: Define the input array int[] numbers = {1, 2, 3, 4}; // Step 2: Convert the array to an IntStream // Step 3: Use map to transform each element to its square // Step 4: Use reduce to sum all the squared elements int sumOfSquares = Arrays.stream(numbers) .map(n -> n * n) // Square each number .reduce(0, (a, b) -> a + b); // Sum them up starting from 0 // Step 5: Print the result System.out.println("Array: " + Arrays.toString(numbers)); System.out.println("Sum of squares (Stream API with map and reduce): " + sumOfSquares); } }
Output
Clear
ADVERTISEMENTS