Check existence of an element in Java ArrayList

Java 8Object Oriented ProgrammingProgramming

The java.util.ArrayList.contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element 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");
      System.out.println("The element C is available in ArrayList? " + aList.contains("C"));
      System.out.println("The element Z is available in ArrayList? " + aList.contains("Z"));
   }
}

Output

The output of the above program is as follows

The element C is available in ArrayList? true
The element Z is available in ArrayList? false

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 “Z” are available in the ArrayList and the result is displayed. 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");
System.out.println("The element C is available in ArrayList? " + aList.contains("C"));
System.out.println("The element Z is available in ArrayList? " + aList.contains("Z"));
raja
Published on 17-Jan-2019 17:39:06
Advertisements