Pin It

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 :



Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot