Learn how to check if an arraylist contains a value in Java with example. Also, learn to check if array contains an element, along with index of element in array.
1. Java ArrayList Contains Example
To check if an ArrayList contains an element, use ArrayList.contains(element) method.
contains(element) method does not take
null
argument, and will throwNullPointerException
isnull
is passed in the method.
1.1. Method Syntax
- Method takes one argument of type Object, whose presence in this list is to be tested.
- Method returns true – if list contains the argument element.
- Method returns false – if list DOES NOT contain the argument element.
- Method throws ClassCastException if the type of the specified element is incompatible with this list.
- Method throws NullPointerException if the specified element is
null
.
boolean contains(Object o);
1.2. Example to check if ArrayList contains element
Given example check if “apple
” is in the list of fruits. Similar check is done for “lion
“, which is not in this list. This example also find the index of element in arraylist.
ArrayList<String> list = new ArrayList<>( Arrays.asList("banana", "guava", "apple", "cheeku") ); list.contains("apple"); //true list.indexOf("apple"); //2 list.contains("lion"); //false list.indexOf("lion"); //-1
2. Java Array Contains Example
To check if an element is in an array, Use Arrays class to convert array to arraylist and apply same contains()
method.
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
3. Check if Java 8 Stream contains an element
Since Java 8, streams also hold elements and you might want to test if stream contains element or not.
Use stream.anyMatch() method which returns whether any elements of this stream match the provided predicate. In predicate simply check the equality to current element in stream and argument element which needs to be find.
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
These were simple examples of arraylist contains() and stream.anyMatch() methods. We also learn to find index of element in array with arraylist indexOf() method.
Happy Learning !!