Check if Array Contains an Item in Java

Learn to check if an array contains an element. Also, learn to find with the index of the element in the array.

2. Using Arrays Class

To check if an element is in an array, we can use Arrays class to convert the array to ArrayList and use the contains() method to check the item’s presence. We can use the indexOf() method to find the index of item in the array.

In the case of an array of custom objects, object equality is checked using the equals() method so the object has implemented the correct and expected equality rules in the overridden equals() method.

String and wrapper classes have already overridden the equals() method so they will work just fine.

String[] fruits = new String[] { "banana", "guava", "apple", "cheeku" };

Arrays.asList(fruits).contains("apple"); // true
Arrays.asList(fruits).indexOf("apple"); // 2

Arrays.asList(fruits).contains("lion"); // false
Arrays.asList(fruits).indexOf("lion"); // -1

2. Using Streams

Since Java 8, we can create a stream of items from the array and test if the stream contains the given item or not.

We can use the stream.anyMatch() method that returns whether any element of this stream match the provided predicate. In predicate simply check the equality to the current element in-stream and argument element which needs to be found.

Nore that Streams also use the equals() method for checking object equality.

String[] fruits = new String[] { "banana", "guava", "apple", "cheeku" };

boolean result = Arrays.asList(fruits)
    .stream()
    .anyMatch(x -> x.equalsIgnoreCase("apple"));	//true

boolean result = Arrays.asList(fruits)
    .stream()
    .anyMatch(x -> x.equalsIgnoreCase("lion"));	//false

3. Using Iteration

Finally, we can always iterate over the array items using the for-each loop and check if the item is present in the array or not.

int[] intArray = new int[]{1, 2, 3, 4, 5};
boolean found = false;
int searchedValue = 2;

for(int x : intArray){
	if(x == searchedValue){
        found = true;
        break;
    }
}

System.out.println(found);

Make sure to change the if-condition to a matching equality check if we are using object types.

String[] stringArray = new String[]{"A", "B", "C", "D", "E"};
boolean found = false;
String searchedValue = "B";

for(String x : stringArray){
    if(x.equals(searchedValue)){
        found = true;
        break;
    }
}

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.