Search an Element in an ArrayList in Java

Java ArrayList class provides the following methods to search an element of ArrayList in Java:
  • contains(Object o)
  • indexOf(Object o)
  • lastIndexOf(Object o)

Search an Element in an ArrayList in Java

package com.javaguides.collections.arraylistexamples;

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

public class SearchElementsInArrayListExample {
    public static void main(String[] args) {
        List < String > programmingLanguages = new ArrayList < > ();
        programmingLanguages.add("C");
        programmingLanguages.add("C++");
        programmingLanguages.add("Java");
        programmingLanguages.add("Kotlin");
        programmingLanguages.add("Python");
        programmingLanguages.add("Perl");
        programmingLanguages.add("Ruby");

        // Check if an ArrayList contains a given element
        System.out.println("Does names array contain \"Bob\"? : " + programmingLanguages.contains("C++"));

        // Find the index of the first occurrence of an element in an ArrayList
        System.out.println("indexOf \"Java\": " + programmingLanguages.indexOf("Java"));
        System.out.println("indexOf \"Python\": " + programmingLanguages.indexOf("Python"));

        // Find the index of the last occurrence of an element in an ArrayList
        System.out.println("lastIndexOf \"Perl\" : " + programmingLanguages.lastIndexOf("Perl"));
        System.out.println("lastIndexOf \"Ruby\" : " + programmingLanguages.lastIndexOf("Ruby"));
    }
}

Output

Does names array contain "Bob"? : true
indexOf "Java": 2
indexOf "Python": 4
lastIndexOf "Perl" : 5
lastIndexOf "Ruby" : 6

Comments