Java – How to check whether particular element is present in an ArrayList ?

In this article, we will discuss an example on how to search whether particular element present in ArrayList or NOT

1. Searching element from ArrayList using contains() method :

Method signature:

boolean contains(Object o);
  • This method is used to search specified object from invoking collection
  • Returns true, if present; otherwise return false


import java.util.ArrayList;

public class SearchElementFromArrayList {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Sundar Pichai");
		al.add("Satya Nadella");
		al.add("Shiv Nadar");
		al.add("Shantanu Narayen");
		al.add("Sundar Pichai"); // duplicate object
		al.add("Francisco D’Souza");
		al.add(null); // null is allowed

		// Iterating using for-loop
		System.out.println("Iterating using enhanced for-loop\n");
		for(String founder : al) {

		// searching element
		boolean boolElement = al.contains("Satya Nadella");
		System.out.println("\n\nWhether element Satya Nadella' "
				+ "is present : " + boolElement);

		// searching and printing in same line
		System.out.println("\n\nWhether element 'Francisco D’Souza' "
				+ "is present : " + al.contains("Francisco D’Souza"));

		// searching and printing in same line
		System.out.println("\n\nWhether element 'Narayan Murthy' "
				+ "is present : " + al.contains("Narayan Murthy"));


Iterating using enhanced for-loop

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Sundar Pichai
Francisco D’Souza

Whether element 'Satya Nadella' is present : true

Whether element 'Francisco D’Souza' is present : true

Whether element 'Narayan Murthy' is present : false

From above example, ArrayList

  • allows duplicate elements
  • null object is allowed
  • while iterating insertion order is maintained

Related Articles:


Happy Coding !!
Happy Learning !!

Java - Comparing two ArrayList objects using containsAll() method
Java - How to get sub-list from ArrayList ?