Skip to Content

Search an element of Java ArrayList Example

  1. /*
  2.   Search an element of Java ArrayList Example
  3.   This Java Example shows how to search an element of java
  4.   ArrayList object using contains, indexOf and lastIndexOf methods.
  5. */
  6.  
  7. import java.util.ArrayList;
  8.  
  9. public class SearchAnElementInArrayListExample {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create an ArrayList object
  14.     ArrayList arrayList = new ArrayList();
  15.    
  16.     //Add elements to Arraylist
  17.     arrayList.add("1");
  18.     arrayList.add("2");
  19.     arrayList.add("3");
  20.     arrayList.add("4");
  21.     arrayList.add("5");
  22.     arrayList.add("1");
  23.     arrayList.add("2");
  24.  
  25.     /*
  26.       To check whether the specified element exists in Java ArrayList use
  27.       boolean contains(Object element) method.
  28.       It returns true if the ArrayList contains the specified objct, false
  29.       otherwise.
  30.     */
  31.    
  32.     boolean blnFound = arrayList.contains("2");
  33.     System.out.println("Does arrayList contain 2 ? " + blnFound);
  34.  
  35.     /*
  36.       To get an index of specified element in ArrayList use
  37.       int indexOf(Object element) method.
  38.       This method returns the index of the specified element in ArrayList.
  39.       It returns -1 if not found.
  40.     */
  41.  
  42.     int index = arrayList.indexOf("4");
  43.     if(index == -1)
  44.       System.out.println("ArrayList does not contain 4");
  45.     else
  46.       System.out.println("ArrayList contains 4 at index :" + index);
  47.      
  48.     /*
  49.       To get last index of specified element in ArrayList use
  50.       int lastIndexOf(Object element) method.
  51.       This method returns index of the last occurrence of the
  52.       specified element in ArrayList. It returns -1 if not found.
  53.     */
  54.  
  55.     int lastIndex = arrayList.lastIndexOf("1");
  56.     if(lastIndex == -1)
  57.       System.out.println("ArrayList does not contain 1");
  58.     else
  59.       System.out.println("Last occurrence of 1 in ArrayList is at index :"
  60.                                                               + lastIndex);
  61.      
  62.   }  
  63. }
  64. /*
  65. Output would be
  66. Does arrayList contain 2 ? true
  67. ArrayList contains 4 at index :3
  68. Last occurrence of 1 in ArrayList is at index :5
  69. */