Java 8 – How to Use Streams to Sum a List of Numbers

Introduction

Java 8 introduced the Stream API, which provides a functional and concise way to process collections of data. One common operation is summing a list of numbers, whether they are integers, doubles, or any other numeric type. The Stream API offers several methods that make summing numbers straightforward and efficient.

In this guide, we’ll explore how to use Java 8 streams to sum a list of numbers, covering different numeric types and scenarios.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Example 1: Summing a List of Integers
    • Example 2: Summing a List of Doubles
    • Example 3: Summing with a Custom Object Field
    • Example 4: Summing with Optional Values
    • Example 5: Handling an Empty List
  • Conclusion

Problem Statement

When working with a list of numbers, you often need to calculate the total sum. Java 8’s Stream API provides a variety of ways to achieve this, depending on the data type and specific requirements.

Example:

  • Problem: Sum all elements in a list of numbers, such as integers or doubles.
  • Goal: Use Java 8 streams to efficiently calculate the sum of elements in a list.

Solution Steps

  1. Sum Integers with mapToInt() and sum(): Use mapToInt() for integers and then sum() to calculate the total.
  2. Sum Doubles with mapToDouble(): Similarly, use mapToDouble() for doubles and then sum().
  3. Sum Custom Object Fields: Extract numeric fields from custom objects and sum them using streams.
  4. Handle Optional Values: Use mapToInt() or mapToDouble() with Optional values.
  5. Handle an Empty List: Ensure the solution handles empty lists gracefully.

Java Program

Example 1: Summing a List of Integers

The simplest case is summing a list of integers using the sum() method.

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

/**
 * Java 8 - Summing a List of Integers
 * Author: https://www.rameshfadatare.com/
 */
public class SumExample1 {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Summing the list of integers
        int sum = numbers.stream()
                         .mapToInt(Integer::intValue)
                         .sum();

        System.out.println("Sum of integers: " + sum);
    }
}

Output

Sum of integers: 15

Explanation

  • mapToInt(Integer::intValue): Converts each Integer in the list to an int primitive.
  • sum(): Computes the sum of the integer stream.

Example 2: Summing a List of Doubles

For lists containing doubles, the process is similar but uses mapToDouble().

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

/**
 * Java 8 - Summing a List of Doubles
 * Author: https://www.rameshfadatare.com/
 */
public class SumExample2 {

    public static void main(String[] args) {
        List<Double> numbers = Arrays.asList(1.5, 2.5, 3.0);

        // Summing the list of doubles
        double sum = numbers.stream()
                            .mapToDouble(Double::doubleValue)
                            .sum();

        System.out.println("Sum of doubles: " + sum);
    }
}

Output

Sum of doubles: 7.0

Explanation

  • mapToDouble(Double::doubleValue): Converts each Double in the list to a double primitive.
  • sum(): Computes the sum of the double stream.

Example 3: Summing with a Custom Object Field

If you have a list of custom objects and want to sum a numeric field, you can use mapToInt() or mapToDouble() accordingly.

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

/**
 * Java 8 - Summing with a Custom Object Field
 * Author: https://www.rameshfadatare.com/
 */
public class SumExample3 {

    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
            new Product("Laptop", 1000),
            new Product("Smartphone", 700),
            new Product("Tablet", 300)
        );

        // Summing the prices of products
        int totalPrice = products.stream()
                                 .mapToInt(Product::getPrice)
                                 .sum();

        System.out.println("Total price: " + totalPrice);
    }
}

class Product {
    private String name;
    private int price;

    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public int getPrice() {
        return price;
    }
}

Output

Total price: 2000

Explanation

  • mapToInt(Product::getPrice): Maps each Product to its price field.
  • sum(): Sums the prices of all products in the list.

Example 4: Summing with Optional Values

If your list contains optional numeric values, you can handle them by using filter() before mapping.

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

/**
 * Java 8 - Summing with Optional Values
 * Author: https://www.rameshfadatare.com/
 */
public class SumExample4 {

    public static void main(String[] args) {
        List<Optional<Integer>> numbers = Arrays.asList(
            Optional.of(10),
            Optional.empty(),
            Optional.of(20),
            Optional.of(30)
        );

        // Summing the present optional integers
        int sum = numbers.stream()
                         .filter(Optional::isPresent)
                         .mapToInt(Optional::get)
                         .sum();

        System.out.println("Sum of present optional integers: " + sum);
    }
}

Output

Sum of present optional integers: 60

Explanation

  • filter(Optional::isPresent): Filters out empty Optional values.
  • mapToInt(Optional::get): Retrieves the integer value from each non-empty Optional.

Example 5: Handling an Empty List

The Stream API handles empty lists gracefully, returning a sum of 0.

import java.util.Collections;
import java.util.List;

/**
 * Java 8 - Handling an Empty List
 * Author: https://www.rameshfadatare.com/
 */
public class SumExample5 {

    public static void main(String[] args) {
        List<Integer> numbers = Collections.emptyList();

        // Summing an empty list
        int sum = numbers.stream()
                         .mapToInt(Integer::intValue)
                         .sum();

        System.out.println("Sum of empty list: " + sum);
    }
}

Output

Sum of empty list: 0

Explanation

  • Handling Empty List: The sum() method returns 0 when the stream is empty, ensuring no errors occur.

Conclusion

Using Java 8 streams to sum a list of numbers is both efficient and elegant. Whether you’re working with integers, doubles, or custom objects, the Stream API provides straightforward methods to calculate sums. These methods handle edge cases like empty lists and optional values, making your code more robust and maintainable.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top