java.util.stream.IntStream/LongStream | Search an element
Last Updated :
11 Dec, 2018
Given an array of elements of integers or long data type, you need to check if a given key is present in this array using pre defined functions in
java.util.stream.IntStream. The java.util.stream.IntStream/LongStream class contains a function anyMatch(), which helps to check if a particular element is present in an array.
Examples:
Input : arr[] = {1,2,3,4,5,6,7} , key = 3
Output : Yes
3 is present in the array.
Input : arr[] = {1,2,3,4,5,6,7} , key = 8
Output : No
The
Stream.anyMatch() method is used to check if the stream contains any such element which matches with a given predicate. It will return true if atleast 1 of the elements of the stream matches with the given predicate condition otherwise it will return false.
Syntax:
boolean anyMatch(Predicate< ? super T > predicate)
Below is a Java program on how to use anyMatch() method with both integer stream and stream of long integers.
Java
// Java program to check if an element is present
// in an array using java.util.stream.IntStream
import java.util.stream.IntStream;
import java.util.stream.LongStream;
class CheckElement
{
public static void main (String[] args)
{
// stream of integer
int num[] = {1,2,3,4,5,6,7};
int key = 3; // key to be searched
boolean result = IntStream.of(num).anyMatch(x -> x == key);
if (result)
System.out.println("Yes");
else
System.out.println("No");
// stream of long
long lnum[] = {1,2,3,4,5,6,7};
// key to be searched
long lkey = 7;
boolean result2 = LongStream.of(lnum).anyMatch(x -> x == lkey);
if (result2)
System.out.println("Yes");
else
System.out.println("No");
}
}
Output:
Yes
Yes
Reference:
anyMatch() java docs