How to filter a List with Lambda

With Java8, Lambda has been introduced and allows to filter ArrayLists without creating a Comparator.

The filter method on the Stream of the list can use the condition to filter on.

Syntax:

list.stream().filter( p -> p <= 40 )

Example:

Lets assume that we want to filter a List of Integer on the values that are less than 40. The code first filters using the Lambda expression, and displays the values in the output.
The code then does the same thing passing an instance of a Predicate<Integer> class. That class has a method test returning a boolean if the condition applies.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class LambdaFilterList {

	public static void main(String[] argv){
		
		List<Integer> list = Arrays.asList( 21, 45, 35, 55 );
		
		System.out.println( "With lambda expression:" );
		list.stream()
			.filter( p -> p  <= 40 )
			.forEach( o -> { 
				System.out.println( o );
			} );
		
		System.out.println( "With predicate:" );
		list.stream().filter( new IntFilter() )
			.forEach( o -> { 
				System.out.println( o );
			} );
	}
}

class IntFilter implements Predicate<Integer> {
	@Override
	public boolean test(Integer t){
    	return t.intValue() < 40;
    }
}

The output will be:

With lambda expression:
21
35
With predicate:
21
35

References:

Lambda Expressions

Share this article:

Recent Comments