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:
- The list of numbers:
[87, 45, 35, 74, 325]
.stream()
creates a stream of elements from the list..limit(2)
restricts the stream to the first two elements:[87, 45]
..mapToInt(Integer::intValue)
convertsInteger
to primitiveint
for summing..sum()
computes the sum of the two numbers:87 + 45 = 132
.- Finally, print the result:
System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);