How to Check If a List Contains a Specific Element in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a specific element exists within a Java List. We will explore different methods for performing this common task when working with collections of data.

You will first learn to use the convenient contains() method provided by the List interface. Following that, you will understand how to manually iterate through a list to check for an element, which can be useful in certain scenarios. Finally, we will cover how to handle the presence of null elements within your list when performing these checks.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/for_loop("For Loop") java/StringManipulationGroup -.-> java/strings("Strings") java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("ArrayList") subgraph Lab Skills java/if_else -.-> lab-559945{{"How to Check If a List Contains a Specific Element in Java"}} java/for_loop -.-> lab-559945{{"How to Check If a List Contains a Specific Element in Java"}} java/strings -.-> lab-559945{{"How to Check If a List Contains a Specific Element in Java"}} java/collections_methods -.-> lab-559945{{"How to Check If a List Contains a Specific Element in Java"}} java/arraylist -.-> lab-559945{{"How to Check If a List Contains a Specific Element in Java"}} end

Use contains() for Element Check

In this step, we will learn how to check if a specific element exists in a Java List using the contains() method. This is a common task when working with collections of data.

First, let's create a new Java file named ListContains.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing ListContains.java.

Now, open the ListContains.java file in the editor and add the following code:

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

public class ListContains {

    public static void main(String[] args) {
        // Create a List of strings
        List<String> fruits = new ArrayList<>();

        // Add some fruits to the list
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Mango");

        // Check if the list contains "Banana"
        boolean hasBanana = fruits.contains("Banana");
        System.out.println("Does the list contain Banana? " + hasBanana);

        // Check if the list contains "Grape"
        boolean hasGrape = fruits.contains("Grape");
        System.out.println("Does the list contain Grape? " + hasGrape);
    }
}

Let's break down this code:

  • import java.util.ArrayList; and import java.util.List;: These lines import the necessary classes to work with Lists.
  • List<String> fruits = new ArrayList<>();: This line creates a new ArrayList which is a type of List that can hold String objects.
  • fruits.add("...");: These lines add elements (fruit names) to our list.
  • fruits.contains("Banana");: This is the core of this step. The contains() method is called on the fruits list. It takes one argument, the element we want to check for. It returns true if the element is found in the list, and false otherwise.
  • boolean hasBanana = ...;: The result of contains() is stored in a boolean variable (hasBanana or hasGrape).
  • System.out.println("...");: These lines print the results to the console.

Save the ListContains.java file (Ctrl+S or Cmd+S).

Now, open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory. If not, type cd ~/project and press Enter.

Compile the Java code using the javac command:

javac ListContains.java

If there are no errors, a ListContains.class file will be created in the ~/project directory.

Finally, run the compiled Java program using the java command:

java ListContains

You should see output similar to this:

Does the list contain Banana? true
Does the list contain Grape? false

This output confirms that the contains() method correctly identified whether "Banana" and "Grape" were present in our list.

Loop Through List Manually

In the previous step, we used the contains() method to check for an element. While contains() is convenient, sometimes you need to examine each element in a list one by one. This is called iterating or looping through a list. In this step, we will learn how to do this using a for loop.

Open the ListContains.java file in your ~/project directory in the WebIDE editor.

We will modify the existing code to loop through the fruits list and print each element. Replace the existing main method with the following code:

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

public class ListContains {

    public static void main(String[] args) {
        // Create a List of strings
        List<String> fruits = new ArrayList<>();

        // Add some fruits to the list
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Mango");

        // Loop through the list using a for loop
        System.out.println("Printing fruits in the list:");
        for (int i = 0; i < fruits.size(); i++) {
            String fruit = fruits.get(i);
            System.out.println(fruit);
        }
    }
}

Let's look at the new parts:

  • System.out.println("Printing fruits in the list:");: This line simply prints a header before we start listing the fruits.
  • for (int i = 0; i < fruits.size(); i++): This is a standard for loop.
    • int i = 0: We start a counter variable i at 0. In programming, we often start counting from 0.
    • i < fruits.size(): The loop continues as long as i is less than the total number of elements in the fruits list. fruits.size() gives us the number of elements.
    • i++: After each time the loop runs, we increase the value of i by 1.
  • String fruit = fruits.get(i);: Inside the loop, fruits.get(i) retrieves the element at the current position i from the list. We store this element in a String variable called fruit.
  • System.out.println(fruit);: This line prints the current fruit to the console.

Save the ListContains.java file.

Now, compile the modified code in the Terminal:

javac ListContains.java

If the compilation is successful, run the program:

java ListContains

You should see the following output:

Printing fruits in the list:
Apple
Banana
Orange
Mango

This shows that our for loop successfully iterated through the list and printed each fruit on a new line. Manually looping through a list like this gives you more control over how you process each element, which can be useful for more complex tasks than just checking for existence.

Handle Null Elements in List

In the real world, lists can sometimes contain "null" values, which represent the absence of a value. If you try to perform operations on a null value without checking, your program can crash with a NullPointerException. In this step, we will learn how to handle null elements when looping through a list.

Open the ListContains.java file in your ~/project directory in the WebIDE editor.

We will modify the code to add a null element to the list and then check for null inside the loop. Replace the existing main method with the following code:

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

public class ListContains {

    public static void main(String[] args) {
        // Create a List of strings
        List<String> fruits = new ArrayList<>();

        // Add some fruits to the list, including a null
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add(null); // Adding a null element
        fruits.add("Orange");
        fruits.add("Mango");

        // Loop through the list and handle null elements
        System.out.println("Printing fruits in the list (handling nulls):");
        for (int i = 0; i < fruits.size(); i++) {
            String fruit = fruits.get(i);

            // Check if the element is null before processing
            if (fruit != null) {
                System.out.println(fruit);
            } else {
                System.out.println("Found a null element");
            }
        }
    }
}

Here's what we've changed:

  • fruits.add(null);: We've added a null value to the list.
  • if (fruit != null): Inside the loop, before we try to print the fruit, we add an if statement to check if the fruit variable is not null.
  • System.out.println(fruit);: This line is inside the if block, so it will only execute if fruit is not null.
  • else { System.out.println("Found a null element"); }: This else block executes if fruit is null, printing a message instead of trying to print the null value itself.

Save the ListContains.java file.

Compile the modified code in the Terminal:

javac ListContains.java

If the compilation is successful, run the program:

java ListContains

You should see the following output:

Printing fruits in the list (handling nulls):
Apple
Banana
Found a null element
Orange
Mango

As you can see, the program now correctly identifies and handles the null element without crashing. Checking for null is a crucial practice in Java programming to prevent errors and make your programs more robust.

Summary

In this lab, we learned how to check if a Java List contains a specific element. We first explored the most straightforward method, using the built-in contains() method, which efficiently determines the presence of an element and returns a boolean result.

We then delved into manually iterating through the list to perform the check, providing a deeper understanding of how the contains() method might work internally. Finally, we addressed the important consideration of handling null elements within the list when performing these checks, ensuring robust and error-free code.