Stream anyMatch() in Java with examples

Last Updated : 24 Dec, 2025

The anyMatch() method of the Stream interface checks whether any element of the stream matches the given condition (predicate). It is a short-circuiting terminal operation, meaning it stops processing as soon as a matching element is found.

Example:

Java
import java.util.*;
class GFG {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3);
        boolean result = list.stream().anyMatch(n -> n > 2);
        System.out.println(result);
    }
}

Output
true

Explanation: stream().anyMatch(n -> n > 2) checks if any element in the list is greater than 2.

Syntax

boolean anyMatch(Predicate<? super T> predicate)

  • Parameters: 'predicate' a condition to test elements of the stream.
  • Return Value: Returns true if any element matches the predicate; otherwise, returns false, including when the stream is empty.

Example 1: This example checks whether any number in the list satisfies the given mathematical condition.

Java
import java.util.*;
class GFG {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(3, 4, 6, 12, 20);
        boolean answer = list.stream()
                             .anyMatch(n -> (n * (n + 1)) / 4 == 5);
        System.out.println(answer);
    }
}

Output
true

Explanation:

  • anyMatch() checks if any element satisfies (n * (n + 1)) / 4 == 5.
  • The lambda n -> (n * (n + 1)) / 4 == 5 defines the condition.
  • Returns true if at least one element matches, otherwise false.

Example 2: This example checks whether any string has an uppercase character at index 1.

Java
import java.util.stream.Stream;
class GFG {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of(
            "Geeks", "fOr", "GEEKSQUIZ", "GeeksforGeeks"
        );
        boolean answer = stream.anyMatch(
            str -> Character.isUpperCase(str.charAt(1))
        );
        System.out.println(answer);
    }
}

Output
true

Explanation:

  • anyMatch() checks if any string has an uppercase character at index 1.
  • The lambda str -> Character.isUpperCase(str.charAt(1)) is used as the predicate.
  • The result is true if at least one string satisfies the condition, otherwise false.

Note: It returns false for empty streams.

Comment