How do I find an element in Java List?



There are couple of ways to find elements in a Java List.

  • Use indexOf() method.

  • Use contains() method.

  • 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.

Example

Following is the example showing various methods to find an element −

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Student> list = new ArrayList<>();
      list.add(new Student(1, "Zara"));
      list.add(new Student(2, "Mahnaz"));
      list.add(new Student(3, "Ayan"));
      System.out.println("List: " + list);
      Student student = new Student(3, "Ayan");
      for (Student student1 : list) {
         if(student1.getId() == 3 && student.getName().equals("Ayan")) {
            System.out.println("Ayan is present.");
         }
      }
      Student student2 = list.stream().filter(s -> {return       s.equals(student);}).findAny().orElse(null);
      System.out.println(student2);
   }
}
class Student {
   private int id;
   private String name;
   public Student(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   @Override
   public boolean equals(Object obj) {
      if(!(obj instanceof Student)) {
         return false;
      }
      Student student = (Student)obj;
      return this.id == student.getId() && this.name.equals(student.getName());
   }
   @Override
   public String toString() {
      return "[" + this.id + "," + this.name + "]";
   }
}

Output

This will produce the following result −

List: [[1,Zara], [2,Mahnaz], [3,Ayan]]
Ayan is present.
[3,Ayan]

Advertisements