Close

Java 8 Streams - IntStream.anyMatch Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.IntStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.IntStreamIntStreamLogicBig

Method:

boolean anyMatch(IntPredicate predicate)

This is a terminal-short-circuiting operation. It checks whether any elements of this IntStream match the provided IntPredicate. 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.intstream;

import java.util.stream.IntStream;

public class AnyMatchExample {

public static void main(String... args) {
IntStream intStream = IntStream.of(1, 2, 3, 2, 5, 4);
boolean b = intStream.anyMatch(AnyMatchExample::evenNumber);
System.out.println(b);

intStream = IntStream.of(1, 2, 3, 2, 5, 4);
b = intStream.anyMatch(AnyMatchExample::negative);
System.out.println(b);
}

private static boolean evenNumber(int i) {
return i % 2 == 0;
}

private static boolean negative(int i) {
return i < 0;
}
}

Output

true
false




For empty stream, anyMatch() method will always return false;

package com.logicbig.example.intstream;

import java.util.stream.IntStream;

public class AnyMatchExample2 {

public static void main(String... args) {
IntStream stream = IntStream.empty();
boolean b = stream.anyMatch(i -> true);
System.out.println(b);
}
}

Output

false




See Also