Languages
[Edit]
EN

Java 8 - sum List of Integers with Stream

0 points
Created by:
Maggotta
319

In this article, we would like to show you how to sum List of Integers with Stream in Java 8.

1. Using Stream.reduce()

In this example, we use Stream.reduce() method where the accumulator function is a lambda expression that adds two Integer values.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        // create list of integers
        List<Integer> numbers = Arrays.asList(1, 2, 3);

        // sum elements
        Integer sum = numbers.stream()
                .reduce(0, Integer::sum);

        // display result
        System.out.println("sum = " + sum);
    }
}

Output:

sum = 6

Note:

Integer sum = numbers.stream()
        .reduce(0, Integer::sum);

is equivalent to:

Integer sum = numbers.stream()
        .reduce(0, (a, b) -> a + b);

2. Using IntStream sum()

In this example, to calculate the sum of a list of integers we use:

  • mapToInt() that converts the stream to an IntStream object,
  • sum() method to calculate the sum of the IntStream's elements.
import java.util.*;

public class Example {

    public static void main(String[] args) {
        // create list of integers
        List<Integer> numbers = Arrays.asList(1, 2, 3);

        // sum elements
        int sum = numbers.stream()
                .mapToInt(Integer::intValue)    // convert to IntStream object
                .sum();                         // sum elements

        // display result
        System.out.println("sum = " + sum);
    }
}

Output:

sum = 6

Note:

In the same way, we can use the mapToLong() and mapToDouble() methods to calculate the sums of longs and doubles.

double sum = numbers.stream()
        .mapToDouble(Double::doubleValue)
        .sum();

3. Using Stream.collect()

In this example, we use collect() method to calculate the sum of a list of integers.

import java.util.*;
import java.util.stream.Collectors;

public class Example {

    public static void main(String[] args) {
        // create list of integers
        List<Integer> numbers = Arrays.asList(1, 2, 3);

        // sum elements
        Integer sum = numbers.stream()
                .collect(Collectors.summingInt(Integer::intValue));

        // display result
        System.out.println("sum = " + sum);
    }
}

Output:

sum = 6

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join