Search element in an array using

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 The class contains a function anyMatch(), which helps to check if a particular element is present in an array.


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.

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 program to check if an element is present
// in an array using


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)
        // 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)



Reference: anyMatch() java docs

This article is contributed by Akash Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Writing code in comment? Please use, generate link and share the link here.