Skip to content
Related Articles

Related Articles

Java Program to Check Whether an Element Occurs in a List

View Discussion
Improve Article
Save Article
  • Last Updated : 07 Jan, 2021

The List Interface in Java represents an ordered collection or sequence. This Interface helps us control where to insert elements and also access elements through an integer index. This Interface is a member of the Java Collections Framework and the java.util package. The classes that implement the List Interface include ArrayList, LinkedList, Stack, and Vector. The Vector class has been deprecated since Java 5.

The classes, ArrayList, LinkedList, and Stack, all use the contains() method to check whether an element occurs in the List.

The contains() method of List interface in Java is used for checking if the specified element exists in the given list or not.

Syntax:

public boolean contains(Object obj)

object-element to be searched for

Parameters: This method accepts a single parameter obj whose presence in this list is to be tested.

Return Value: It returns true if the specified element is found in the list else it returns false.

Steps:

  1. Import the necessary packages. In this case, we need to import the java.util package.
  2. Create an ArrayList with the help of the List Interface.
  3. Add elements to the ArrayList using the add() method.
  4. Check whether the required element occurs in the ArrayList with the help of the contains() method.

Example:

Java




// Java program to check whether an element
// is present in an ArrayList
  
// importing package
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // Creating an ArrayList of String type
        List<String> GFG = new ArrayList<String>();
  
        // Adding elements to the ArrayList
        GFG.add("Welcome");
        GFG.add("To");
        GFG.add("Geeks");
        GFG.add("For");
        GFG.add("Geeks");
  
        //  Using contains() method to check whether the
        //  particular
        // element is present in the List or not
        System.out.println(GFG.contains("Welcome")); 
        System.out.println(GFG.contains("Java")); 
    }
}


Output

true
false
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!