Course contentsShow
← Java
Lesson 1539 of 2,87033. Streams API: Terminal OperationsFree lesson

Combining Match Operations with Complex Predicates

Apply match operations with composite predicates using and, or, and negate to express sophisticated matching logic.

Combining Match Operations with Complex Predicates

What you'll learn: How to use and(), or(), and negate() to build sophisticated matching logic with anyMatch, allMatch, and noneMatch.

Now that you understand the three match operations, you can supercharge them by combining multiple conditions into complex predicates. Java's Predicate interface provides methods to compose predicates logically, enabling you to express intricate matching criteria without cluttering your code.

Building Complex Predicates

Instead of writing complicated lambda expressions, you can combine simple predicates using:

  • and() – Both conditions must be true
  • or() – At least one condition must be true
  • negate() – Inverts the predicate's result
Predicate<String> startsWithA = s -> s.startsWith("A");
Predicate<String> longerThanFive = s -> s.length() > 5;

// Combine predicates
Predicate<String> complexPredicate = startsWithA.and(longerThanFive);

List<String> words = List.of("Apple", "Apricot", "Ant", "Banana");

boolean hasMatch = words.stream()
    .anyMatch(complexPredicate);  // true (Apricot matches both)

Real-World Example

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

List<Integer> numbers = List.of(-4, 6, 12, 15, 20);

// All positive even numbers OR all larger than ten?
boolean result = numbers.stream()
    .allMatch(isPositive.and(isEven).or(largerThanTen));  // false

Why This Matters

Think of predicates as building blocks, like LEGO pieces. Instead of creating one massive, unreadable condition, you assemble small, reusable predicates into complex logic. This makes your code clearer, testable, and maintainable.

Key Takeaway: Use and(), or(), and negate() to compose simple predicates into sophisticated matching conditions, making your stream match operations both powerful and readable.