Close

Java 8 Streams - Stream.anyMatch Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

boolean anyMatch(Predicate<? super T> predicate)

This is a terminal-short-circuiting operation. It checks whether any elements of this stream match the provided predicate. It will terminate (short-circuiting) with a result of 'true' when the very first element matches the provided predicate.

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


Examples


package com.logicbig.example;

import java.util.stream.Stream;


public class AnyMatchExample {

public static void main(String[] args) {
Stream<String> stream = Stream.of("one", "two", "three", "four");
boolean match = stream.anyMatch(s -> s.contains("our"));
System.out.println(match);
}
}

Output

true
Original Post




An empty stream will always return false;

package com.logicbig.example.stream;

import java.util.Arrays;

public class AnyMatchExample {

public static void main(String... args) {
boolean b = Arrays.asList()
.stream()
.anyMatch(e -> true);
System.out.println(b);
}
}

Output

false




See Also