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

Introduction

Java 8 introduced the Stream API, a powerful and functional approach to processing collections of data. One of the common operations you may need to perform is summing a list of numbers. The Stream API provides various methods that make this task simple and efficient, regardless of whether you are working with integers, doubles, or custom object fields.

In this guide, we’ll explore different ways to sum a list of numbers using Java 8 streams.

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 Fields in a List of Custom Objects
    • Example 4: Handling an Empty List
  • Conclusion

Problem Statement

When dealing with a list of numbers, you often need to compute the total sum. Java 8’s Stream API offers a clean and concise way to accomplish this task.

Example:

  • Problem: Sum all the elements in a list of numbers.
  • Goal: Use Java 8’s Stream API to compute the sum efficiently.

Solution Steps

  1. Sum Integers Using Streams: Learn how to sum integers using the Stream API’s mapToInt and sum methods.
  2. Sum Doubles Using Streams: Apply a similar approach for lists of doubles with mapToDouble.
  3. Sum Fields in Custom Objects: Sum values of a particular field from a list of custom objects.
  4. Handle Empty Lists: Ensure the solution handles empty lists correctly.

Java Program

Example 1: Summing a List of Integers

The most straightforward case involves summing a list of integers.

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 its primitive int value.
  • sum(): Computes the sum of the integer values in the stream.

Example 2: Summing a List of Doubles

For lists containing doubles, the approach 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 its primitive double value.
  • sum(): Computes the sum of the double values in the stream.

Example 3: Summing Fields in a List of Custom Objects

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

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

/**
 * Java 8 - Summing Fields in a List of Custom Objects
 * 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): Extracts the price field from each Product object and converts it to an int.
  • sum(): Sums the prices of all products in the list.

Example 4: Handling an Empty List

The Stream API gracefully handles empty lists, 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 SumExample4 {

    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

  • Empty List Handling: The sum() method returns 0 when the stream is empty, ensuring that no errors occur and providing a meaningful result.

Conclusion

Java 8’s Stream API provides an efficient and concise way to sum a list of numbers, whether they are integers, doubles, or custom object fields. By using methods like mapToInt(), mapToDouble(), and sum(), you can perform summation operations cleanly and effectively. The Stream API also handles edge cases like empty lists gracefully, making it a robust solution for numerical computations in Java.

Leave a Comment

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

Scroll to Top