In this example we are going to learn how to find out if an ArrayList
object contains the specified element. To check if an ArrayList
object contains the specified element we can use the contains(Object o)
method. This method returns a boolean
true
when the specified element is found in the ArrayList
, otherwise return false
. The method returns true
if and only if the list contains at least one element, where the element equals to the item in the list.
Let’s see the code snippet below to demonstrate it.
package org.kodejava.util;
import java.util.ArrayList;
import java.util.List;
public class ArrayListContainsExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
// Check to see if the list contains "Item 1".
String itemToFind = "Item 1";
System.out.println("contains(" + itemToFind + "): " + list.contains(itemToFind));
// Check to see if the list contains "Item 20".
itemToFind = "Item 20";
System.out.println("contains(" + itemToFind + "): " + list.contains(itemToFind));
}
}
The output of the code snippet above are:
contains(Item 1): true
contains(Item 20): false
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
If we take pojo in list then how to check the existing particular element of list.
Hi Amrendra,
You need to implements the
equals()
method in your pojo so that thelist.contains()
method knows if the list already contains the same pojo. And when you implement theequals()
method you will also need to implement thehashCode()
method.