Check if a Java ArrayList contains a given item or not

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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");
raja
Published on 11-Jan-2019 06:45:24
Advertisements