Java Stream anyMatch() With Examples

In Java Stream API anyMatch(Predicate<? super T> predicate) method is used to check whether any element of this stream matches the provided predicate.

anyMatch() method in Java

Syntax of anyMatch() method is as given below.

boolean anyMatch(Predicate<? super T> predicate)

Method returns a boolean value true if any element of the stream matches the provided predicate, otherwise false.

anyMatch() is a short-circuiting terminal operation. It's a terminal operation means the stream pipeline is considered consumed, and can no longer be used. It is also short-circuiting which means when presented with infinite input, it may terminate in finite time.

anyMatch() method may not evaluate the predicate on all elements as soon as a matching element is found method returns.

If the stream is empty then false is returned and the predicate is not evaluated.

anyMatch() Java examples

1. In the first example anyMatch() method is used to check if a List of strings has any element matching the given condition (whether any name starts with “A”).

public class AnyMatchDemo {

  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Peter", "Ram", "Ajay", "Dan");
    boolean result = nameList.stream().anyMatch(n -> n.startsWith("A"));
    System.out.println(result);
  }
}
Output
true

2. In this example anyMatch() method is used to check if list of Users has any user with age greater than 60.

User class
public class User {
  private String name;
  private int age;
  User(String name, int age){
    this.name = name;
    this.age = age;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  @Override
  public String toString() {
    return getName() + " " + getAge() + " \n";
  } 
}
public class AnyMatchDemo {

  public static void main(String[] args) {
      List<User> userList = Arrays.asList(new User("Peter", 59),
                new User("Ram", 19),
                new User("Mahesh", 32),
                new User("Scott", 32));
      boolean result = userList.stream().anyMatch(u -> u.getAge() > 60);
      System.out.println(result);
  }
}

Output
false

That's all for the topic Java Stream anyMatch() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like