Interface for Filtering with Lambdas in Java


Create a Java program to demonstrate the use of an interface for filtering with lambdas

  • The Filter<T> interface defines a single abstract method test that takes an item of type T and returns a boolean indicating whether the item passes the filter criteria.
  • In the Main class, a list of integers (numbers) is created using List.of() method.
  • An instance of Filter<Integer> is created using a lambda expression n -> n % 2 == 0, which filters even numbers.
  • The stream() method is invoked on the numbers list to create a stream of elements.
  • The filter() intermediate operation is applied to the stream, passing the evenFilter::test method reference as the predicate. This filters the elements of the stream based on the condition specified in the evenFilter instance.
  • The collect() terminal operation is used to collect the filtered elements into a new list (evenNumbers).
  • Finally, the even numbers are printed to the console.

Source Code

import java.util.List;
import java.util.stream.Collectors;
interface Filter<T>
{
	boolean test(T item);
}
 
public class Main
{
	public static void main(String[] args)
	{
		List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
 
		Filter<Integer> evenFilter = n -> n % 2 == 0;
		List<Integer> evenNumbers = numbers.stream()
			.filter(evenFilter::test)
			.collect(Collectors.toList());
 
		System.out.println("Even Numbers : " + evenNumbers);
	}
}

Output

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

Example Programs