How to Check If a Specified Element Exists in a HashSet in Java


In this example, we will learn how to check if a specified element exists in a HashSet in Java.

Source Code

package com.beginner.examples;

import java.util.HashSet;

public class ElementInHashSet {

  public static void main(String[] args) {
    // Create a HashSet object
    HashSet sets = new HashSet();
    sets.add("A");
    sets.add("B");

    boolean b = sets.contains("A"); // check if a specified element exists in a HashSet
    System.out.println(b);
  }
}

Output:

true

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments