Java Online Compiler
Example: Sum of Squares using Java 8 Streams (map and sum) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Squares using Java 8 Streams (map and sum) 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 sum to get the total of all squared elements int sumOfSquares = Arrays.stream(numbers) .map(n -> n * n) // Square each number .sum(); // Sum all numbers in the stream // Step 5: Print the result System.out.println("Array: " + Arrays.toString(numbers)); System.out.println("Sum of squares (Stream API with map and sum): " + sumOfSquares); } }
Output
Clear
ADVERTISEMENTS