✅ 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:
- numbers.stream(): Converts the list of integers into a Stream of Integer objects.
- limit(2): Limits the stream to only the first two elements of the list.
- mapToInt(Integer::intValue): Converts each
Integerobject to primitiveintfor efficient summation. - sum(): Calculates the sum of the remaining elements in the stream.
- Finally, the result is printed using
System.out.println().