How to find an element in a List with Java?


The List interface extends Collection interface and represents a collection storing a sequence of elements. User of a list has quite precise control over where an element to be inserted in the List. These elements are accessible by their index and are searchable. ArrayList is the most popular implementation of the List interface among the Java developers.

In Java List, there are couple of ways to find an element.

  • Use indexOf() method. - This method returns the index of the element if present otherwise -1.

  • Use contains() method. - This methods returns true if element is present otherwise false.

  • Loop through the elements of a list and check if element is the required one or not.

  • Loop through the elements of a list using stream and filter out the element.

In this article, we're going to cover each of the above methods mentioned in examples.

Example 1

Following is an example showing the usage of indexOf() and contains() methods to find an element in a list −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("Zara");
      list.add("Mahnaz");
      list.add("Ayan");
     
      System.out.println("List: " + list);
      String student = "Ayan";
     
      if(list.indexOf(student) != -1) {
         System.out.println("Ayan is present.");
      }
      if(list.contains(student)) {
         System.out.println("Ayan is present.");
      }
   }
}

Output

This will produce the following result −

List: [Zara, Mahnaz, Ayan]
Ayan is present.
Ayan is present.

Example 2

Following is an example showing the usage of iteration and streams to find an element in a list −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("Zara");
      list.add("Mahnaz");
      list.add("Ayan");
     
      System.out.println("List: " + list);
      String student = "Ayan";
     
      for (String student1 : list) {
         if(student1 == "Ayan") {
            System.out.println("Ayan is present.");
         }
      }
      String student2 = list.stream().filter(s -> {return s.equals(student);}).findAny().orElse(null);
      System.out.println(student2);
   }
}

Output

This will produce the following result −

List: [Zara, Mahnaz, Ayan]
Ayan is present.
Ayan

Updated on: 26-May-2022

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements