Open In App

Check if a value is present in an Array in Java

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array, the task is to write a Java program to check whether a specific element is present in this Array or not.

Examples: 

Input: arr[] = [5, 1, 1, 9, 7, 2, 6, 10], key = 7
Output: Is 7 present in the array: true

Input: arr[] = [-1, 1, 5, 8], key = -2
Output: Is -2 present in the array: false

An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be quickly sorted or searched. All the items of the array are stored at contiguous memory locations. 

Approaches

There are numerous approaches to check whether a specific element is present in this Array or not in Java. These are – 

  • Using the Linear Search method
  • Using the Binary Search method
  • Using List.contains() method
  • Using Stream.anyMatch() method

1. Using Linear Search Method: 

In Linear Search, the list or array is traversed sequentially, and every element is checked. 

Syntax: 

for (int element : arr) {
if (element == toCheckValue) {
return true;
}
}

Example: 

Java
// Java program to check whether
// an element is present in array or not

import java.util.Arrays;
import java.util.stream.IntStream;

class GFG {

    // Function return true if given element
    // found in array
    private static void check(int[] arr, int toCheckValue)
    {
        // check if the specified element
        // is present in the array or not
        // using Linear Search method
        boolean test = false;
        for (int element : arr) {
            if (element == toCheckValue) {
                test = true;
                break;
            }
        }

        // Print the result
        System.out.println("Is " + toCheckValue
                           + " present in the array: " + test);
    }

    public static void main(String[] args)
    {

        // Get the array
        int a[] = { 5, 1, 1, 9, 7, 2, 6, 10 };

        // Get the value to be checked
        int ele = 7;

        // Check if this value is
        // present in the array or not
        check( a,ele );
    }
}

Output
Is 7 present in the array: true

Complexity of the above method:

Time Complexity: O(N)
Auxiliary Space: O(1)

2. Using Binary Search Method: 

In Binary Search Method, search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
In this example, the Arrays.binarySearch() method is used for Binary Search.

Syntax: 

public static int 
binarySearch(data_type arr, data_type key)

Example:

Java
// Java program to check whether
// an element is present in array or not

import java.util.Arrays;
import java.util.stream.IntStream;

class GFG {

    // Function return true if given element
    // found in array
    private static void check(int[] arr, int toCheckValue)
    {
        // sort given array
        Arrays.sort(arr);

        // check if the specified element
        // is present in the array or not
        // using Binary Search method
        int res = Arrays.binarySearch(arr, toCheckValue);

        boolean test = res >= 0 ? true : false;

        // Print the result
        System.out.println("Is " + toCheckValue
                           + " present in the array: " + test);
    }

    public static void main(String[] args)
    {

        // Get the array
        int a[] = { 5, 1, 1, 9, 7, 2, 6, 10 };

        // Get the value to be checked
        int ele = 7;

        // Check if this value is
        // present in the array or not
        check(a, ele);
    }
}

Output
Is 7 present in the array: true

Complexity of the above method:

Time Complexity: O(nlog(n))
Auxiliary Space: O(1)

3. Using List.contains() Method: 

List contains() method in Java is used for checking if the specified element exists in the given list or not.

Syntax: 

public boolean contains(Object)

where object-element to be searched for.

Example: 

Java
// Java program to check whether
// an element is present in array or not

import java.util.Arrays;

class GFG {

    // Function return true if given element
    // found in array
    private static void check(Integer[] arr, int toCheckValue)
    {
        // check if the specified element
        // is present in the array or not
        // using contains() method
        boolean test = Arrays.asList(arr)
                  .contains(toCheckValue);

        // Print the result
        System.out.println("Is " + toCheckValue
                           + " present in the array: " + test);
    }

    public static void main(String[] args)
    {

        // Get the array
        Integer a[] = { 5, 1, 1, 9, 7, 2, 6, 10 };

        // Get the value to be checked
        int ele = 7;

        // Check if this value is
        // present in the array or not
        check(a, ele);
    }
}

Output
Is 7 present in the array: true

Complexity of the above method:

Time Complexity: O(N)
Auxiliary Space: O(1)

4. Using Stream.anyMatch() Method: 

Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result.

Syntax: 

boolean anyMatch(Predicate<T> predicate)

Where T is the type of the input to the predicate
and the function returns true if any elements of
the stream match the provided predicate,
otherwise false.

Example 1: Using Stream.of() method to create Stream

Java
// Java program to check whether
// an element is present in array or not
import java.util.Arrays;
import java.util.stream.IntStream;

class GFG {

    // Function return true if given element
    // found in array
    private static void check(int[] arr, int toCheckValue)
    {
        // check if the specified element
        // is present in the array or not
        // using anyMatch() method
        boolean test = IntStream.of(arr)
                  .anyMatch(x -> x == toCheckValue);

        // Print the result
        System.out.println("Is " + toCheckValue
                           + " present in the array: " + test);
    }

    public static void main(String[] args)
    {

        // Get the array
        int a[] = { 5, 1, 1, 9, 7, 2, 6, 10 };

        // Get the value to be checked
        int ele = 7;

        // Check if this value is
        // present in the array or not
        check(a, ele);
    }
}

Output
Is 7 present in the array: true

Complexity of the above method:

Time Complexity: O(N)
Auxiliary Space: O(1)

Example 2: Using Arrays.stream() method to create Stream

Java
// Java program to check whether
// an element is present in array or not

import java.util.Arrays;
import java.util.stream.IntStream;

class GFG {

    // Function return true if given element
    // found in array
    private static void check(int[] arr, int toCheckValue)
    {
        // check if the specified element
        // is present in the array or not
        // using anyMatch() method
        boolean test
            = Arrays.stream(arr)
                  .anyMatch(x -> x == toCheckValue);

        // Print the result
        System.out.println("Is " + toCheckValue
                           + " present in the array: " + test);
    }

    public static void main(String[] args)
    {

        // Get the array
        int a[] = { 5, 1, 1, 9, 7, 2, 6, 10 };

        // Get the value to be checked
        int ele = 7;

        // Check if this value is
        // present in the array or not
        check(a, ele);
    }
}

Output
Is 7 present in the array: true

Complexity of the above method:

Time Complexity: O(N)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Check whether the Average Character of the String is present or not
Given a string of alphanumeric characters, the task is to check whether the average character of the string is present or not. Average character refers to the character corresponding to the ASCII value which is the floor of the average value of the ASCII values of all characters in the string. Examples: Input: abcdefOutput: d YesExplanation: string
7 min read
Sum of all perfect numbers present in an array
Given an array arr[] containing N positive integer. The task is to find the sum of all the perfect numbers from the array. A number is perfect if it is equal to the sum of its proper divisors i.e. the sum of its positive divisors excluding the number itself. Examples: Input: arr[] = {3, 6, 9} Output: 6Proper divisor sum of 3 = 1 Proper divisor sum
5 min read
Sum of all mersenne numbers present in an array
Given an array of integers arr[], the task is to find the sum of all the Mersenne numbers from the array. A number is a Mersenne number if it is greater than 0 and is one less than some power of 2. First few Mersenne numbers are 1, 3, 7, 15, 31, 63, 127, ... Examples: Input: arr[] = {17, 6, 7, 63, 3} Output: 73 Only 7, 63 and 3 are Mersenne numbers
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Sum of all Palindrome Numbers present in a Linked list
Given a linked list with integer node values, the task is to find the sum of all Palindrome Numbers present as Node values.Examples: Input: 13 -> 212 -> 22 -> 44 -> 4 -> 3 Output: 285 Explanation: The sum of palindrome numbers {22, 212, 44, 4, 3} is 285Input: 19 -> 22 -> 141 Output: 163 Approach: In order to solve this problem
8 min read
Find max or min value in an array of primitives using Java
Java as a whole is a language that generally requires a lot of coding to execute specific tasks. Hence, having shorthand for several utilities can be beneficial. One such utility, to find maximum and minimum element in array is explained in this article using "aslist()". aslist() type casts a list from the array passed in its argument. This functio
2 min read
Check whether array has all identical elements using Arrays.asList() and HashSet in Java
Given an array arr[] of N elements, the task is to check whether the array have all same (identical) elements or not without using the loop. If all elements are same then print Yes otherwise print No. Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: Yes The given array has all identical elements i.e. 2. Input: arr[] = {2, 3, 3, 3, 3, 2, 2} Output:
2 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java Math toIntExact(long value) Method
The java.lang.Math.toIntExact() is a built-in math function in java which returns the value of the long argument.It throws an exception if the result overflows an int.As toIntExact(long value) is static, so object creation is not required. Syntax : public static int toIntExact(long value) Parameter : value : the long value Return : This method retu
1 min read
EnumMap containsValue(value) method in Java
The Java.util.EnumMap.containsValue(value) method in Java is used to determine whether one or more key of the map is associated with a given value or not. It takes the value as a parameter and returns True if that value is mapped by any of the keys in the EnumMap. Syntax: boolean containsValue(Object value) Parameter: The method accepts one paramet
2 min read
Replace null values with default value in Java Map
Given a Map with null values in it, the task is to replace all the null values with a default value. Examples: Input: map = {1=1, 2=2, 3=null, 4=4, 5=null, 6=null}, defaultValue = 0 Output: {1=1, 2=2, 3=0, 4=4, 5=0, 6=0} Input: map = {1=A, 2=B, 3=null, 4=D, 5=null, 6=null}, defaultValue = 'Z' Output: {1=A, 2=B, 3=Z, 4=D, 5=Z, 6=Z} Approach: Get the
3 min read
Properties contains(value) method in Java with Examples
The contains(value) method of Properties class is used to check if this Properties object contains any mapping of this value for any key present in it. It takes this value to be compared as a parameter and returns a boolean value as a result. This method is more expensive than the containsKey() method. Also, this method is the same in working as th
2 min read
Properties containsKey(value) method in Java with Examples
The containsKey(value) method of Properties class is used to check if this Properties object contains any mapping of this Key for any key present in it. It takes this value to be compared as parameter and returns a boolean value as result. Syntax: public Object containsKey(Object value) Parameters: This method accepts a parameter value which is the
2 min read
Properties containsValue(value) method in Java with Examples
The containsValue(value) method of Properties class is used to check if this Properties object contains any mapping of this Value. It takes this value to be compared as parameter and returns a boolean value as result. Syntax: public Object containsValue(Object value) Parameters: This method accepts a parameter value which is the value to be searche
2 min read
Properties equals(value) method in Java with Examples
The equals(value) method of Properties class is used to check for equality between two properties. It verifies whether the elements of one properties object passed as a parameter is equal to the elements of this properties or not. Syntax: public boolean equals(Object value) Parameters: This method accepts a parameter value of this Properties type a
2 min read
AbstractMap.SimpleEntry setValue(V value) Method in Java with Examples
AbstractMap.SimpleEntry<K, V> is used to maintain a key and a value entry. The value can be changed using the setValue method. This class facilitates the process of building custom map implementations. setValue(V value) method of AbstractMap.SimpleEntry<K, V> used to replace the current value of map with the specified value passed as pa
2 min read
HashMap replace(key, value) method in Java with Examples
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Syntax: public V replace(K key, V value) Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced. value:
3 min read
HashMap putIfAbsent(key, value) method in Java with Examples
The putIfAbsent(K key, V value) method of HashMap class is used to map the specified key with the specified value, only if no such key exists (or is mapped to null) in this HashMap instance. Syntax: public V putIfAbsent(K key, V value)Parameters: This method accepts two parameters: key: which is the key with which provided value has to be mapped.va
3 min read
HashMap merge(key, value, BiFunction) method in Java with Examples
The merge(Key, Value, BiFunctional) method of the HashMap class is used to combine multiple mapped values for a key using the given mapping function. A bucket is actually an index of the array, that array is called a table in HashMap implementation. So table[0] is referred to as bucket0, table[1] as bucket1, and so on. If the key is not present or
3 min read
Initialize a list in a single line with a specified value using Java Stream
Given a value N, the task is to create a List having this value N in a single line in Java using Stream. Examples: Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] Approach: Get the value N Generate the Stream using generate() method Set the size of the List to be created as 1 using limit() method Pass the value to be mappe
2 min read
How to find the Entry with largest Value in a Java Map
Given a map in Java, the task is to find out the entry in this map with the highest value. Illustration: Input : Map = {ABC = 10, DEF = 30, XYZ = 20} Output : DEF = 30Input : Map = {1 = 40, 2 = 30, 3 = 60} Output : 3 = 60 Methods: There can be several approaches to achieve the goal that are listed as follows: Simple iterative approach via for each
4 min read
Difference Between keySet() vs value() Method in Java Map
Map Interface is present in Java.util package, which provides mainly three methods KeySet(),entrySet() and values(). These methods are used to retrieve the keys of the map, key-value pairs of the map, and values of the map respectively. Since these methods are part of Map Interface, so we can use can these methods with all the classes implementing
4 min read
Difference Between value() vs entrySet() Method in Java Map
Map Interface is present in Java.util package, which provides mainly three methods KeySet(),entrySet() and values(). These methods are used to retrieve the keys of the map, key-value pairs of the map, and values of the map respectively. Since these methods are part of Map Interface, so we can use can these methods with all the classes implementing
5 min read
Enum with Customized Value in Java
Prerequisite : enum in Java By default enums have their own string values, we can also assign some custom values to enums. Consider below example for that. Examples: enum Fruits { APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”); } In above example we can see that the Fruits enum have three members i.e APPLE, BANANA and GRAPES with have their own di
2 min read
Java is Strictly Pass by Value!
In order to understand more of how the java is processing the parameter in methods and functions, lets compare the java program with a C++ code which would make it more clear and helps you get the major difference between how the parameters are being passed to any methods or functions wrt passing parameters by value and with reference and it is the
6 min read
How to Read and Print an Integer value in Java
The given task is to take an integer as input from the user and print that integer in Java language. In the below program, the syntax and procedures to take the integer as input from the user are shown in Java language. Steps for InputThe user enters an integer value when asked.This value is taken from the user with the help of nextInt() method of
2 min read
Check if a String Contains Only Alphabets in Java Using Lambda Expression
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th
3 min read
Check if a String Contains only Alphabets in Java using Regex
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a text. It is widely used to define a constraint on strings such as a password. Regular Expressions are provided under java.util.regex package. For any string, here the task is to check whether a string contains only alphabe
2 min read
Check if a String starts with any of the given prefixes in Java
Given a String and an array of prefixes. The task is to check whether the given String starts with any of the given prefixes or not. Example: Input: String = "GeeksforGeeks", Prefixes = {"Geeks", "for", "Gfor"} Output: true Input: String = "GeeksforGeeks", Prefixes = {"Freaks", "for", "Freak"} Output: false Below are the following approaches that c
4 min read
How to check if a key exists in a HashMap in Java
Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: true Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10 Output: false Using Iterator (Not Efficient): Get the HashMap and the Key Create an iterator to iterate over the
4 min read
three90RightbarBannerImg