Using Lambda Expressions with filter
You'll learn how to write inline lambda expressions as predicates to filter streams in real-world scenarios.
Now that you understand filter takes a Predicate, it's time to master writing lambda expressions directly inside filter() calls. Lambda expressions let you define filtering logic inline without creating separate method references or variables.
The Pattern
The basic structure is:
stream.filter(element -> booleanExpression)
The lambda receives each element and returns true to keep it or false to discard it.
Filtering Numbers
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Keep only even numbers
Stream<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0);
// Keep numbers greater than 5
Stream<Integer> large = numbers.stream()
.filter(n -> n > 5);
// Combine conditions
Stream<Integer> evenAndLarge = numbers.stream()
.filter(n -> n % 2 == 0 && n > 5);
Filtering Strings
List<String> words = List.of("apple", "banana", "kiwi", "pear");
// Keep strings longer than 4 characters
Stream<String> longWords = words.stream()
.filter(s -> s.length() > 4);
// Keep strings starting with 'a'
Stream<String> startsWithA = words.stream()
.filter(s -> s.startsWith("a"));
Filtering Custom Objects
// Assuming a Person class with getName() and getAge()
List<Person> people = /* ... */;
// Keep adults
Stream<Person> adults = people.stream()
.filter(person -> person.getAge() >= 18);
// Keep people with short names
Stream<Person> shortNames = people.stream()
.filter(person -> person.getName().length() <= 5);
Key Takeaway: Lambda expressions in filter() let you write concise inline predicates—the pattern element -> condition is your filtering workhorse for numbers, strings, and custom objects alike.