Check if a Java ArrayList contains a given item or not
The java.util.ArrayList.contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList; import java.util.List; public class Demo < public static void main(String[] args) < List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); if(aList.contains("C")) System.out.println("The element C is available in the ArrayList"); else System.out.println("The element C is not available in the ArrayList"); if(aList.contains("H")) System.out.println("The element H is available in the ArrayList"); else System.out.println("The element H is not available in the ArrayList"); >>
Output
The element C is available in the ArrayList The element H is not available in the ArrayList
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “H” are available in the ArrayList. Then an if statement is used to print if they are available or not. A code snippet which demonstrates this is as follows −
List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); if(aList.contains("C")) System.out.println("The element C is available in the ArrayList"); else System.out.println("The element C is not available in the ArrayList"); if(aList.contains("H")) System.out.println("The element H is available in the ArrayList"); else System.out.println("The element H is not available in the ArrayList");
Learning faster. Every day.
Interface List
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.
The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.
The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.
The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.
The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.
Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.
Unmodifiable Lists
- They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
- They disallow null elements. Attempts to create them with null elements result in NullPointerException .
- They are serializable if all elements are serializable.
- The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
- The lists and their subList views implement the RandomAccess interface.
- They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
- They are serialized as specified on the Serialized Form page.
This interface is a member of the Java Collections Framework.
Best way to find whether a collection does or does not contain an element with a specific desired quality
It seems to be a very common thing to have to tell whether some list or set contains at least one object matching a given condition, yet my prior searching and reading have never found a satisfactory best practice or design pattern to speak of. In the situations I am thinking of, merely using «contains» is not sufficient, as the test we want to perform is not strictly based on the equals method of the class in question. Some things I have seen:
// for-each with break private boolean doFoosHaveGoodQuality(List candidates) < boolean foundIt = false; for (Foo item: candidates) < if (>) < fountIt = true; break; >> return foundIt; > // while-do with index counter private boolean doFoosHaveGoodQuality(List candidates) < boolean foundIt = false; int index = 0; while(!fountIt && index < candidates.size() - 1) < Foo item = candidates.get(index++); if (>) < fountIt = true; >> return foundIt; >
Both of these get the job done and quit as soon as a success is found, possibly saving some time if we are lucky enough to have the desired item early in the list. However, both require looping the entire list in order to get a false result Another technique I’ve seen in some circumstances is that at the same time the original List
I would say the first approach is simpler, and more maintainable. The second may give a marginal performance benefit, which could certainly matter if this is very frequent logic run in a performance-sensitive environment against thousands of items.
3 Answers 3
Algorithmically, the for-each and the while-with-indexing version implement linear search. This is okay for small collections or when you only do such a check very occasionally, but if it’s an important building block of your program, you’d want a dedicated mapping structure which speeds up these queries by doing something fundamentally different from linear search. Examples include binary search trees (where you need to define a consistent ordering) and hash tables (where you need to define a consistent hash function). For most predicates this is trivial, for others it would be some extra code (defining FooKey ), and for yet others it is hard or completely impractical. This is a judgement call depending on the criteria by which you search.
When you’ve decided on linear search, there are several options to implement it (provided there isn’t already a good implementation — if so, prefer that!). The for-each variant is quite general and IMHO elegant: It works with any iterable, it doesn’t even have to be backed by a concrete collection (cf. streams in Java 8). The while loop with indexing, on the other hand, is very restricted: It’s offensively slow for containers that can’t do random access (e.g. linked lists), and it doesn’t work at all for things that can’t be indexed. I would never recommend this one. There are probably other variations, but they are even more specialized. If you implement linear search, implement it for iterables.
Another issue is how you supply the predicate. You could write essentially the same loop again and again with only the condition different. But this is error prone, verbose, and inefficient. There should be only one copy of this loop, with the condition being passed as parameter. If your language (version) can do this, use a first-class function/lambda. Otherwise, you could emulate it with an interface and anonymous classes. Once you do this, Map s lose some of their appeal: It’s no longer a long loop versus map.get(whatIWant) , it’s list.find(whatIWant) . Of course they still have a performance benefit for large collections.
Side note: The loops can be slightly simpler, for example I’d write the for-each loop as:
private boolean doFoosHaveGoodQuality(List candidates) < for (Foo item: candidates) < if (>) < return true; >> return false; >
How to check if Java list contains an element or not?
List provides a method contains() to check if list contains that element or not. It utilizes equals() method so we need to override the equals() method in the element type.
Syntax
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
Parameters
Returns
True if this list contains the specified element.
Throws
- ClassCastException − If the type of the specified element is incompatible with this list (optional).
- NullPointerException − If the specified element is null and this list does not permit null elements (optional).
Example
The following example shows how to check elements to be present in a list using contains() method.
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Student s1 = new Student(1, "Zara"); Student s2 = new Student(2, "Mahnaz"); Student s3 = new Student(3, "Ayan"); Student s4 = new Student(4, "Raman"); Listlist = new ArrayList<>(Arrays.asList(s2,s1,s3)); System.out.println("List: " + list); System.out.println("Zara is present: " + list.contains(s1)); System.out.println("Raman is present: " + list.contains(s4)); > > class Student < private int rollNo; private String name; public Student(int rollNo, String name) < this.rollNo = rollNo; this.name = name; >public int getRollNo() < return rollNo; >public void setRollNo(int rollNo) < this.rollNo = rollNo; >public String getName() < return name; >public void setName(String name) < this.name = name; >@Override public boolean equals(Object obj) < if(!(obj instanceof Student)) < return false; >Student student = (Student)obj; return this.rollNo == student.getRollNo() && this.name.equals(student.getName()); > @Override public String toString() < return "[" + this.rollNo + "," + this.name + "]"; >>
Output
This will produce the following result −
List: [[2,Mahnaz], [1,Zara], [3,Ayan]] Zara is present: true Raman is present: false