How to Check If HashSet contains a Specified Element in Java


In this example we will show how to check if an specified element is contained in Java HashSet with contains method.

Source Code

package com.beginner.examples;

import java.util.HashSet;

public class CheckHashSetContainsElement {

	public static void main(String[] args) {
		// Create a HashSet object
		HashSet hSet = new HashSet();

		// Add elements
		hSet.add("A");
		hSet.add("B");
		hSet.add("C");

		/*
		 * Use the Contains() method to check whether the specified element
		 * exists in the collection.
		 */
		boolean b = hSet.contains("A");
		boolean b1 = hSet.contains("D");
		System.out.println("Element A:" + b + "nElement D:" + b1);

	}
}

Output:

Element A:true
Element D:false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments