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

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);

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

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

✅ Output:

Sum of first two numbers = 132

✅ Explanation:

  1. The list of numbers: [87, 45, 35, 74, 325]
  2. .stream() creates a stream of elements from the list.
  3. .limit(2) restricts the stream to the first two elements: [87, 45].
  4. .mapToInt(Integer::intValue) converts Integer to primitive int for summing.
  5. .sum() computes the sum of the two numbers:
    87 + 45 = 132.
  6. Finally, print the result: System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

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