How to Check If a Set 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 collection in Java. We will focus on using the contains() method, which is available for all collection types. You will practice using contains() with different element types and learn how to handle null elements. By the end of this lab, you will be proficient in determining the presence of elements within Java collections.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("Encapsulation") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("ArrayList") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/collections_methods -.-> lab-559973{{"How to Check If a Set Contains a Specific Element in Java"}} java/encapsulation -.-> lab-559973{{"How to Check If a Set Contains a Specific Element in Java"}} java/arraylist -.-> lab-559973{{"How to Check If a Set Contains a Specific Element in Java"}} java/object_methods -.-> lab-559973{{"How to Check If a Set Contains a Specific Element in Java"}} end

Use contains() for Element Check

In this step, we will explore how to check if a specific element exists within a collection in Java. Collections are fundamental data structures used to group multiple elements into a single unit. Java provides various types of collections, such as Lists, Sets, and Maps.

One common task when working with collections is to determine if a particular element is present. Java's Collection interface, which is the root interface for all collection types, provides a convenient method for this purpose: contains().

The contains() method takes one argument, the element you want to check for, and returns a boolean value: true if the element is found in the collection, and false otherwise.

Let's create a simple Java program to demonstrate how to use the contains() method with an ArrayList, which is a common type of List.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    import java.util.ArrayList;
    import java.util.List;
    
    public class HelloJava {
        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 new code:

    • import java.util.ArrayList; and import java.util.List;: These lines import the necessary classes to work with Lists and ArrayLists.
    • List<String> fruits = new ArrayList<>();: This line creates a new ArrayList that can hold String objects and assigns it to a variable named fruits.
    • fruits.add("Apple"); and similar lines: These lines add elements (strings representing fruit names) to our fruits list.
    • boolean hasBanana = fruits.contains("Banana");: This line calls the contains() method on the fruits list, checking if the string "Banana" is present. The result (true or false) is stored in a boolean variable hasBanana.
    • System.out.println("Does the list contain Banana? " + hasBanana);: This line prints the result of the check for "Banana".
    • boolean hasGrape = fruits.contains("Grape"); and the following println: These lines do the same check for "Grape", which is not in our list.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    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 that "Banana" is in the list and "Grape" is not.

Understanding how to check for the presence of elements is a fundamental skill when working with collections in Java. In the next steps, we will explore more aspects of the contains() method and how it behaves with different scenarios.

Test with Different Element Types

In the previous step, we used the contains() method with a List of String objects. The contains() method is versatile and can be used with collections that store different types of elements, such as numbers, custom objects, or even other collections.

When using contains(), Java relies on the equals() method of the objects within the collection to determine if the element being searched for is a match. For primitive types (like int, double, boolean), their corresponding wrapper classes (Integer, Double, Boolean) are used, and their equals() methods compare the values. For objects, the default equals() method checks if the two object references point to the same memory location. However, many classes (like String, Integer, etc.) override the equals() method to compare the actual content or value of the objects.

Let's modify our program to work with a List of Integer objects and see how contains() behaves.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the current code with the following:

    import java.util.ArrayList;
    import java.util.List;
    
    public class HelloJava {
        public static void main(String[] args) {
            // Create a List of integers
            List<Integer> numbers = new ArrayList<>();
    
            // Add some numbers to the list
            numbers.add(10);
            numbers.add(25);
            numbers.add(5);
            numbers.add(50);
    
            // Check if the list contains 25
            boolean hasTwentyFive = numbers.contains(25);
            System.out.println("Does the list contain 25? " + hasTwentyFive);
    
            // Check if the list contains 100
            boolean hasOneHundred = numbers.contains(100);
            System.out.println("Does the list contain 100? " + hasOneHundred);
    
            // Check if the list contains the Integer object with value 5
            boolean hasFiveObject = numbers.contains(Integer.valueOf(5));
            System.out.println("Does the list contain Integer object with value 5? " + hasFiveObject);
        }
    }

    In this code:

    • We create a List that specifically holds Integer objects: List<Integer> numbers = new ArrayList<>();.
    • We add integer values to the list using numbers.add(). Java automatically converts the primitive int values (10, 25, 5, 50) into Integer objects (this is called autoboxing).
    • We use numbers.contains(25) and numbers.contains(100) to check for the presence of integer values. Again, Java autoboxes the primitive int values 25 and 100 into Integer objects before performing the check.
    • We also explicitly create an Integer object using Integer.valueOf(5) and check if the list contains this specific object.
  3. Save the file.

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    You should see output similar to this:

    Does the list contain 25? true
    Does the list contain 100? false
    Does the list contain Integer object with value 5? true

This demonstrates that contains() works correctly with Integer objects, comparing their values. The contains() method effectively uses the equals() method of the elements in the collection and the element being searched for.

In the next step, we will explore a special case: handling null elements with the contains() method.

Handle Null Elements

In Java, collections can sometimes contain null elements. It's important to understand how the contains() method behaves when dealing with null.

The good news is that the contains() method is designed to handle null elements gracefully. If a collection contains null, calling contains(null) will return true. If the collection does not contain null, it will return false. This is consistent with how equals() is generally implemented for null (any object's equals(null) should return false, but null.equals(anyObject) would throw a NullPointerException if not handled internally by the collection's contains implementation).

Let's modify our program to include and check for null elements.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the current code with the following:

    import java.util.ArrayList;
    import java.util.List;
    
    public class HelloJava {
        public static void main(String[] args) {
            // Create a List that can contain null
            List<String> mixedList = new ArrayList<>();
    
            // Add some elements, including null
            mixedList.add("First");
            mixedList.add(null); // Adding a null element
            mixedList.add("Second");
            mixedList.add(null); // Adding another null element
            mixedList.add("Third");
    
            // Check if the list contains null
            boolean hasNull = mixedList.contains(null);
            System.out.println("Does the list contain null? " + hasNull);
    
            // Check if the list contains a non-existent element
            boolean hasFourth = mixedList.contains("Fourth");
            System.out.println("Does the list contain Fourth? " + hasFourth);
    
            // Check if the list contains "First"
            boolean hasFirst = mixedList.contains("First");
            System.out.println("Does the list contain First? " + hasFirst);
        }
    }

    In this code:

    • We create a List called mixedList.
    • We add some String elements and also explicitly add null using mixedList.add(null);.
    • We then use mixedList.contains(null) to check if the list contains the null value.
    • We also perform checks for a non-existent string ("Fourth") and an existing string ("First") to see the results alongside the null check.
  3. Save the file.

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. Run the program:

    java HelloJava

    You should see output similar to this:

    Does the list contain null? true
    Does the list contain Fourth? false
    Does the list contain First? true

This output confirms that contains() correctly identifies the presence of null within the list. It's important to be aware that collections can contain null (depending on the specific collection type and how it's used), and contains() provides a reliable way to check for it.

You have now learned how to use the contains() method to check for elements in Java collections, including different data types and the special case of null. This is a valuable tool for working with collections in your Java programs.

Summary

In this lab, we learned how to check if a collection contains a specific element in Java using the contains() method. We saw how this method, available through the Collection interface, returns a boolean indicating the presence of the element. We demonstrated its usage with an ArrayList and observed how it correctly identifies existing and non-existing elements.

We also explored how the contains() method works with different data types and how to handle null elements within a collection. This hands-on experience provided a practical understanding of a fundamental operation when working with Java collections.