Write a Java program using Lambda Expression to find the sum of all positive integers in a list of numbers
The java program that calculates the sum of positive integers in a list of numbers using Java Streams. Here's an explanation of the code:
- An ArrayList named numbers is created to store a list of integers. Some of the integers in the list are positive, and some are negative.
- System.out.println("Given Numbers : " + numbers); prints the original list of numbers.
- The program uses Java Streams to filter and calculate the sum of positive integers:
- numbers.stream(): This converts the numbers list into a stream of integers.
- .filter(n -> n > 0): This is a filter operation that retains only the positive integers in the stream. The condition n > 0 checks if a number is greater than 0.
- .mapToInt(Integer::intValue): This converts the filtered stream of integers into an IntStream.
- .sum(): This calculates the sum of the positive integers in the IntStream.
- System.out.println("Sum of Positive Integers : " + sum_positives); prints the sum of positive integers.
Source Code
import java.util.ArrayList;
import java.util.List;
public class SumOfPositiveIntegers
{
public static void main(String[] args)
{
List<Integer> numbers = new ArrayList<>();
numbers.add(-2);
numbers.add(5);
numbers.add(-1);
numbers.add(8);
numbers.add(-10);
numbers.add(12);
System.out.println("Given Numbers : " + numbers);
int sum_positives = numbers.stream().filter(n -> n > 0).mapToInt(Integer::intValue).sum();
System.out.println("Sum of Positive Integers : " + sum_positives);
}
}
Output
Given Numbers : [-2, 5, -1, 8, -10, 12]
Sum of Positive Integers : 25