Java Stream noneMatch()

In this guide, you will learn about the Stream noneMatch() method in Java programming and how to use it with an example.

1. Stream noneMatch() Method Overview

Definition:

The Stream.noneMatch() method is a terminal operation that checks whether no elements of the stream match the provided predicate. In other words, it returns true if none of the elements of the stream satisfy the given condition.

Syntax:

boolean noneMatch(Predicate<? super T> predicate)

Parameters:

- predicate: a non-interfering, stateless predicate to apply to elements of the stream.

Key Points:

- It's a terminal operation and, therefore, ends the stream pipeline.

- The method returns a boolean value.

- It's a short-circuiting operation. The operation stops processing as soon as it finds an element that matches the condition.

- If the stream is empty, then the result is true (because no elements matched the predicate).

- It processes elements in the order they appear until it finds a matching element or all elements have been processed.

2. Stream noneMatch() Method Example

import java.util.stream.Stream;

public class StreamNoneMatchExample {
    public static void main(String[] args) {
        Stream<String> cityStream = Stream.of("New York", "Los Angeles", "Chicago", "Houston", "Phoenix");

        // Check if no city names start with the letter "D"
        boolean noCityStartsWithD = cityStream.noneMatch(city -> city.startsWith("D"));

        System.out.println("Are there no city names that start with the letter 'D'? " + noCityStartsWithD);
    }
}

Output:

Are there no city names that start with the letter 'D'? true

Explanation:

In the provided example: We have a stream of city names. Using noneMatch(), we check if there are no city names that start with the letter "D". Since none of the cities in the stream ("New York", "Los Angeles", "Chicago", "Houston", "Phoenix") start with the letter "D", the result is true.

Comments