BudiBadu Logo

Combine Multiple Filter Conditions

Java Hard 0 views

Practice Java Predicate composition to build complex filtering conditions from simple predicates using and, or, and negate operations. This functional approach creates reusable, testable filter components that can be combined in various ways.

You will design predicate chains that express business rules clearly and compose them to handle complex filtering scenarios. This technique is valuable for validation, searching, and conditional processing.

Example 1:

Input: numbers = [1, 2, 3, 4, 5, 6]
Output: [2, 4, 6]
Explanation: Filter using isEven predicate.

Example 2:

Input: numbers = [5, 10, 15, 20, 25]
Output: [10, 20]
Explanation: Combine isEven AND greaterThanFive predicates.

Example 3:

Input: numbers = [1, 2, 3, 4, 5]
Output: [1, 3, 5]
Explanation: Negate isEven predicate to get odd numbers.

Algorithm Flow

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

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());
    }
}