Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to check whether an ArrayList contains an element specified in Java ?.

Program to implement how to check whether an ArrayList contains an element specified in Java.

package com.hubberspot.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListContainsDemo {

 public static void main(String[] args) {

  // Create a ArrayList object which can store 
  // collection of String objects 
  List< String > stringList = new ArrayList< String >();

  // Add few String objects to it
  stringList.add("Neha");
  stringList.add("Abhishek");
  stringList.add("Deepali");
  stringList.add("Snehal");
  stringList.add("Vijay");
  stringList.add("Aditya");

  // Lets create an String object and check 
  // whether ArrayList created above contains it
  String name = "Neha";

  // In order to check whether ArrayList contains an element
  // or not we use list's contains(), which 
  // Returns true if this list contains the specified element.  
  if( stringList.contains(name) ) {

   System.out.println("The list contains the element : " + name);

  }
  else {

   System.out.println("The list does not contains the element : " + name);

  }

  name = "Dhwani";

  if( stringList.contains(name) ) {

   System.out.println("The list contains the element : " + name);

  }
  else {

   System.out.println("The list does not contains the element : " + name);

  }

 }

}



Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot