Code Logo

Combine Multiple Filter Conditions

Published at13 Jan 2026
Hard 14 views
Like14

You are given a list of integers and need to keep only the values that satisfy both filter conditions used by the Java solution.

Based on the judge data, the numbers must be even and at least 20. That is why [5, 10, 15, 20, 25, 30] becomes [20, 30], and [12, 14, 16, 18] becomes an empty list even though all of those numbers are even.

This problem is really about combining simple predicate rules into one stronger filter. A number only stays in the output if it passes every required condition.

So the task is to filter the list using composed Java predicates and return the numbers that satisfy the full combined rule.

Example Input & Output

Example 1
Input
numbers = [5, 10, 15, 20, 25, 30]
Output
[20, 30]
Explanation

Only values that are even and at least 20 remain.

Example 2
Input
numbers = [12, 14, 16, 18]
Output
[]
Explanation

All values are even, but none reach the minimum threshold of 20.

Example 3
Input
numbers = [20, 40, 60]
Output
[20, 40, 60]
Explanation

Every value satisfies both filter conditions, so the list stays the same.

Algorithm Flow

Recommendation Algorithm Flow for Combine Multiple Filter Conditions
Recommendation Algorithm Flow for Combine Multiple Filter Conditions

Solution Approach

The Java feature this problem is trying to practice is predicate composition. Instead of writing one long condition inline, we can build small reusable predicates and then combine them with methods like and().

For this problem, the real rule from the tests is: keep numbers that are even and greater than or equal to 20. That naturally splits into two smaller predicates. One checks parity, for example n -> n % 2 == 0. The other checks the minimum threshold, for example n -> n >= 20.

Once those exist, Java lets us combine them cleanly:

Predicate<Integer> isEven = n -> n % 2 == 0;

Predicate<Integer> atLeastTwenty = n -> n >= 20;

Predicate<Integer> combined = isEven.and(atLeastTwenty);

Then the stream pipeline can apply that one combined predicate inside filter and collect the result list.

This approach is useful because the business rule reads clearly and can be adjusted without rewriting the whole stream. The runtime is still O(n) because each number is checked once. The main value is clarity: Java predicates let you express "must satisfy both conditions" in a very direct way.

Best Answers

java - Approach 1
import java.util.List;
import java.util.stream.Collectors;
import java.util.function.Predicate;

class Solution {
    public List<Integer> filterNumbers(List<Integer> numbers) {
        Predicate<Integer> isGreaterThan10 = n -> n > 10;
        Predicate<Integer> isEven = n -> n % 2 == 0;
        Predicate<Integer> isDivisibleBy5 = n -> n % 5 == 0;
        
        return numbers.stream()
                     .filter(isGreaterThan10.and(isEven).and(isDivisibleBy5))
                     .collect(Collectors.toList());
    }
}