Streams – allMatch() operation

Stream allMatch() in Java is a short-circuiting terminal operation. Returns whether all elements of this stream match the provided predicate. 

The allMatch() method returns true if all elements match the given predicate, otherwise false.

Syntax

  boolean allMatch(Predicate<? super T> predicate)


Java Stream allMatch() operation – examples

Example 1
A simple program that checks if all elements of the stream are even numbers:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20));

    System.out.println(numbers.stream()
            .allMatch(number -> number % 2 == 0));
  }
}

Output: true


Example 2
A program that checks if all users have a premium membership type:

class Test {

  public static void main(String[] args) {
    boolean areAllPremiumMembers = getAllUsers().stream()
            .allMatch(user -> user.getMembershipType().equals("premium"));

    System.out.println(areAllPremiumMembers);
  }

  private static List<User> getAllUsers() {
    List<User> users = new ArrayList<>();
    users.add(new User("John", "john123", "premium", "5th Avenue"));
    users.add(new User("Megan", "meganusr", "standard", "New Light Street"));
    users.add(new User("John", "john123", "premium", "5th Avenue"));
    users.add(new User("Melissa", "mellisa1", "premium", "Ser Kingston Street"));

    return users;
  }
}

class User {
  private String name;
  private String username;
  private String membershipType;
  private String address;

  public User(String name, String username, String membershipType, String address) {
    this.name = name;
    this.username = username;
    this.membershipType = membershipType;
    this.address = address;
  }

  public String getMembershipType() {
    return membershipType;
  }
}

Output: false


That’s it!

 

Leave a Reply

Your email address will not be published.