Java List sum the squares of all odd integers via Stream

Description

Java List sum the squares of all odd integers via Stream

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()//from  w  ww .j av a  2s.  c o  m
              .filter(n -> n % 2 == 1)
              .map(n -> n * n)
              .reduce(0, Integer::sum);

    System.out.println("Sum = " + sum);
  }
}



PreviousNext

Related