ArrayList

Search elements in ArrayList example

With this example we are going to demonstrate how to search elements in a ArrayList. In short, to search elements in a ArrayList you should:

  • Create a new ArrayList.
  • Populate the arrayList with elements, using add(E e) API method of ArrayList.
  • Check if an element exists in the arrayList, withcontains(Object element) API method of ArrayList. The method returns true if the element exists in the arrayList and false otherwise.
  • Invoke indexOf(Object element) API method of ArrayList, to get the index of the first occurance of the specified element in ArrayList or -1 if the specific element is not found.
  • To get the index of the last occurance of this element in the arrayList we can use lastIndexOf(Object element) method.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.ArrayList;
 
public class SearchElementsInArrayList {
 
  public static void main(String[] args) {
 
    // Create an ArrayList and populate it with elements
    ArrayList arrayList = new ArrayList();
    arrayList.add("element_1");
    arrayList.add("element_2");
    arrayList.add("element_3");
    arrayList.add("element_1");
 
    /*

boolean contains(Object element) operation returns true 

if the ArrayList contains the specified object, false otherwise.
    */
    boolean found = arrayList.contains("element_2");
    System.out.println("Found element_2 : " + found);
 
    /*

int indexOf(Object element) operation returns the index of the 

first occurance of the specified element in ArrayList or -1 if 

the specific element is not found. To get the index of the last 

occurance of the specified element in ArrayList use the

int lastIndexOf(Object element) operation instead.
    */
    int index = arrayList.indexOf("element_3");
    System.out.println("Found element_3 : " + (index == -1?false:true) + ", in position : " + index);
 
    int lastIndex = arrayList.lastIndexOf("element_1");
    System.out.println("Found element_1 : " + (lastIndex == -1?false:true) + ", in position : " + lastIndex);
 
  }   
}

Output:

Found element_2 : true
Found element_3 : true, in position : 2 
Found element_1 : true, in position : 3

 
This was an example of how to search elements in a ArrayList in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button