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


The java program that uses Java Streams to filter and collect odd 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, which is 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 Odd_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> odd_num = num.stream().filter(number -> number % 2 != 0).collect(Collectors.toList());: This line uses a stream to filter odd 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 odd numbers into a new list named odd_num.
    • System.out.println("Odd Numbers: " + odd_num); : This line prints the list of odd numbers.

Source Code

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

Output

Odd Numbers: [1, 3, 5, 7, 9]

Example Programs