- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you check if an element is present in a list in Java?
Elements can be checked from a list using indexOf() or contains() methods.
Syntax - indexOf() method
int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
Parameters
o − Element to search for.
Returns
The index of the first occurrence of the specified element in this list, or -1 if this list does not contain the 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).
Syntax - contains() method
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
o − 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
Following is the example finding elements from a list using various methods −
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); System.out.println("Ayan is present: " + list.contains("Ayan")); int index = list.indexOf("Ayan"); System.out.println("Ayan is present at: " + index); } }
Output
This will produce the following result −
List: [Zara, Mahnaz, Ayan] Ayan is present: true Ayan is present at: 2
To Continue Learning Please Login
Login with Google