Check if ArrayList contains a Specific Object
To check if ArrayList contains a specific object or element, use ArrayList.contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.
ArrayList.contains() – Reference to Syntax and Examples.
Following is a quick code example to use ArrayList.contains() method.
boolean b = arraylist_1.contains(element);
Example 1 – Check if Element is present in ArrayList
In the following program, we shall take an ArrayList of strings, and check if the string object “banana” is present in the list.
Java Program
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> arraylist_1 = new ArrayList<String>(
Arrays.asList("apple", "banana", "mango", "orange"));
String element = "banana";
if(arraylist_1.contains(element)) {
System.out.println(element+" is present in the list.");
} else {
System.out.println(element+" is not present in the list.");
}
}
}
Output
banana is present in the list.
Example 2 – Check if Element is present in ArrayList – Negative Scenario
In the following program, we shall take an ArrayList of strings, and check if the string object “lemon” is present in the list.
Java Program
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> arraylist_1 = new ArrayList<String>(
Arrays.asList("apple", "banana", "mango", "orange"));
String element = "lemon";
if(arraylist_1.contains(element)) {
System.out.println(element+" is present in the list.");
} else {
System.out.println(element+" is not present in the list.");
}
}
}
As the specified element is not present in the ArrayList, contains() method returns false, and the else block executes.
Output
lemon is not present in the list.
Conclusion
In this Java Tutorial, we learned how to check if given element is present in the ArrayList or not, using contains() method.