Sum of Unique Numbers in a List in Java

Problem :

How do you calculate the sum of only unique elements from a list using Java 8 Streams?

✅ Example:

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

public class SumOfUniqueNumbers {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(23, 45, 23, 15, 15, 78, 23, 85, 65);

        // Calculate sum of unique numbers
        int uniqueNumbersSum = numbers.stream()
            .distinct()                     // Get only unique elements
            .mapToInt(Integer::intValue)    // Convert Integer to int
            .sum();                         // Sum the unique numbers

        System.out.println("Sum of unique numbers: " + uniqueNumbersSum);
    }
}

✅ Explanation:

  1. numbers.stream(): Creates a stream from the list of integers.
  2. distinct(): Removes duplicate elements from the stream, keeping only unique values.
  3. mapToInt(Integer::intValue): Converts Integer objects to primitive int for efficient processing.
  4. sum(): Computes the sum of the resulting IntStream.
  5. Finally, the result is printed with System.out.println().

✅ Output:

Sum of unique numbers: 311

Because the unique numbers are:

23 + 45 + 15 + 78 + 85 + 65 = 311

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

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