How to check if Java list contains an element or not?


List provides a method contains() to check if list contains that element or not. It utilizes equals() method so we need to override the equals() method in the element type.

Syntax

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Parameters

  • − Element whose presence in this list is to be tested.

Returns

True if this list contains the specified element.

Throws

  • ClassCastException  − If the type of the specified element is incompatible with this list (optional).

  • NullPointerException  − If the specified element is null and this list does not permit null elements (optional).

Example

The following example shows how to check elements to be present in a list using contains() method.

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      Student s1 = new Student(1, "Zara");
      Student s2 = new Student(2, "Mahnaz");
      Student s3 = new Student(3, "Ayan");
      Student s4 = new Student(4, "Raman");
      List<Student> list = new ArrayList<>(Arrays.asList(s2,s1,s3));
      System.out.println("List: " + list);
      System.out.println("Zara is present: " + list.contains(s1));
      System.out.println("Raman is present: " + list.contains(s4));
   }
}
class Student {
   private int rollNo;
   private String name;
   public Student(int rollNo, String name) {
      this.rollNo = rollNo;
      this.name = name;
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   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.rollNo == student.getRollNo() && this.name.equals(student.getName());
   }
   @Override
   public String toString() {
      return "[" + this.rollNo + "," + this.name + "]";
   }
}

Output

This will produce the following result −

List: [[2,Mahnaz], [1,Zara], [3,Ayan]]
Zara is present: true
Raman is present: false

Updated on: 09-May-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements