Streams – noneMatch() operation

Stream noneMatch() in Java is a short-circuiting terminal operation. Returns whether no elements of this Stream match the provided predicate. Terminal operation means that we can not execute any other operation after it.

The noneMatch() method returns true if none of the elements match the given predicate, otherwise false.

Syntax

boolean noneMatch(Predicate<? super T> predicate)


Java Stream noneMatch() operation – examples

Example 1
Check that there is no number lower than 5.

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(12, 17, 20, 8, 92, 15, 9, 31, 7));

    System.out.println(numbers.stream()
            .noneMatch(number -> number < 5));
  }
}

Output: true


Example 2
Check that there is no student with a grade lower than 7.

class Test {

  public static void main(String[] args) {
    System.out.println(getStudents().stream()
            .noneMatch(student -> student.getGrade() < 7));
  }

  private static List<Student> getStudents() {
    List<Student> students = new ArrayList<>();
    students.add(new Student("Steve", "Rogers", 8));
    students.add(new Student("John", "Doe", 5));
    students.add(new Student("Melissa", "Smith", 7));
    students.add(new Student("Megan", "Norton", 7));
    students.add(new Student("Tom", "Johnson", 9));

    return students;
  }
}

class Student {
  private String firstName;
  private String lastName;
  private int grade;

  public Student(String firstName, String lastName, int grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
  }

  public int getGrade() {
    return this.grade;
  }
}

Output: false


That’s it!

 

Leave a Reply

Your email address will not be published.