How to Remove Specified Element from Java HashSet


In this example, we will learn how to remove a specified object or element contained in Java HashSet object by the remove() method.

Source Code

package com.beginner.examples;

import java.util.HashSet;

public class RemoveSpecifiedElementOfHashSet {

	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");

		//Remove using the remove() method from the HashSet class
		boolean b = hSet.remove("A");

		System.out.println(b + "n" + hSet);

	}

}

Output:

[B, C]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments