Find the Sum of the First Two Elements in a List Using Java 8 Streams

✅ Problem :

Using Java 8 Streams, how do you find the sum of the first two numbers in a list?

✅ Example:

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

public class SumOfFirstTwoNumbers {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(87, 45, 35, 74, 325);

        // Find sum of the first two numbers
        int sumOfTwoNumbers = numbers.stream()
            .limit(2)                      // Take only the first two elements
            .mapToInt(Integer::intValue)  // Convert Integer to int
            .sum();                       // Sum the elements

        System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);
    }
}

✅ Output:

Sum of first two numbers = 132

(Since 87 + 45 = 132)


✅ Explanation:

  1. numbers.stream(): Converts the list of integers into a Stream of Integer objects.
  2. limit(2): Limits the stream to only the first two elements of the list.
  3. mapToInt(Integer::intValue): Converts each Integer object to primitive int for efficient summation.
  4. sum(): Calculates the sum of the remaining elements in the stream.
  5. Finally, the result is printed using System.out.println().

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 *