Write a Java program using Lambda Expression to multiply and sum all elements in a list of integers


The java program that demonstrates how to use Java Streams to compute the product and sum of elements in a list of integers. Here's an explanation of the code:

  • import java.util.ArrayList;: This line imports the ArrayList class from the java.util package, which is used to create a list of integers.
  • import java.util.List;: This line imports the List interface from the java.util package, which is used to work with lists.
  • The Sum_Multiple class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List<Integer> num = new ArrayList<>();: This line creates an ArrayList named num to store integers.
    • num.add(1);, num.add(2);, num.add(3);, num.add(4);, and num.add(5);: These lines add integers (1, 2, 3, 4, and 5) to the num list.
    • int mul = num.stream().reduce(1, (a, b) -> a * b);: This line uses a stream to calculate the product of all elements in the num list. It uses the reduce operation with an initial value of 1, and a lambda expression (a, b) -> a * b to multiply the accumulated result (a) with each element (b). The result is stored in the mul variable.
    • System.out.println("Multiplication of Elements : " + mul);: This line prints the result of the multiplication operation.
    • int sum = num.stream().reduce(0, (a, b) -> a + b);: This line uses a stream to calculate the sum of all elements in the num list. It uses the reduce operation with an initial value of 0, and a lambda expression (a, b) -> a + b to add the accumulated result (a) to each element (b). The result is stored in the sum variable.
    • System.out.println("Sum of Elements : " + sum); : This line prints the result of the summation operation.

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class Sum_Multiple
{
	public static void main(String[] args)
	{
		List<Integer> num = new ArrayList<>();
		num.add(1);
		num.add(2);
		num.add(3);
		num.add(4);
		num.add(5);
 
		int mul = num.stream().reduce(1, (a, b) -> a * b); // Multiply all elements together
 
		System.out.println("Multiplication of Elements : " + mul);
 
		int sum = num.stream().reduce(0, (a, b) -> a + b); // Sum all elements
 
		System.out.println("Sum of Elements : " + sum);
	}
}

Output

Multiplication of Elements : 120
Sum of Elements : 15

Example Programs