Java - Computing the Sum of the Squares of All Odd Integers From 1 to 5

Introduction

For better performance, you could have used an IntStream in this example.

Demo

import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    // Get a list of integers from 1 to 5
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

    // Compute the sum of the squares of all odd integers in the list
    int sum = numbers.stream().filter(n -> n % 2 == 1).map(n -> n * n)
        .reduce(0, Integer::sum);

    System.out.println("Sum = " + sum);
  }/*from w  w w  . j a  v a 2s  . co  m*/
}

Result

Related Topic