Check if Array Contains an Item in Java

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

1. 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 the predicate, check the equality to the current element in-stream and the argument element which needs to be found.

Note 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 whether the item is present in the array.

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 !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode