Write a Java program using Lambda Expression to filter out even numbers from a list of integers


The java program that uses Java Streams to filter and collect even numbers from a list of integers. Here's an explanation of the code:

  • import java.util.Arrays;: This line imports the Arrays class from the java.util package. It's used to create a list of integers from an array.
  • import java.util.List;: This line imports the List class from the java.util package, which is used to work with lists.
  • import java.util.stream.Collectors;: This line imports the Collectors class from the java.util.stream package, which is used to collect elements from a Stream into a collection.
  • The Even_Numbers class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);: This line creates a list of integers named num containing the numbers from 1 to 10.
    • List<Integer> even_num = num.stream().filter(number -> number % 2 == 0).collect(Collectors.toList());: This line uses a stream to filter even numbers from the num list. The filter operation applies a lambda expression to each number, and the numbers that satisfy the condition (number % 2 == 0) are retained. The collect operation collects the filtered even numbers into a new list named even_num.
    • System.out.println("Even Numbers: " + even_num); : This line prints the list of even numbers.

Source Code

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class Even_Numbers
{
	public static void main(String[] args)
	{
		List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
 
		List<Integer> even_num = num.stream().filter(number -> number % 2 == 0).collect(Collectors.toList());
 
		System.out.println("Even Numbers: " + even_num);
	}
}

Output

Even Numbers: [2, 4, 6, 8, 10]

Example Programs