How to delete an element and delete all elements of HashSet

In this article, we will discuss an example of HashSet on how to delete a particular element and later deleting all elements

 

HashSet :

  • remove(Object) –> to delete a particular element by specifying object name
  • clear() –> deletes all elements present in HashSet
  • Note: Both above method inherited from Collection interface

 

Delete an element and delete all elements :

Below HashSet example depicts,

  • Deleting a particular element by specifying object name
  • Deleting all elements or clearing HashSet

DeleteAndDeleteAllElementsOfHashSet.java

package in.bench.resources.java.collections;

import java.util.HashSet;

public class DeleteAndDeleteAllElementsOfHashSet {

	public static void main(String[] args) {

		// creating HashSet object of type String
		HashSet<String> hs = new HashSet<String>();

		// adding elements to HashSet object - 8
		hs.add("Sundar Pichai");
		hs.add("Satya Nadella");  
		hs.add("Shiv Nadar");  
		hs.add("Shantanu Narayen");
		hs.add("Sundar Pichai"); // duplicate object
		hs.add("Francisco D’Souza");
		hs.add(null); // one null is allowed
		hs.add(null); // Again, null is allowed - duplicate

		System.out.println("Size of an HashSet is : " 
				+ hs.size());

		// Iterating using enhanced for-loop
		System.out.println("\nIterating using enhanced for-loop\n");
		for(String founder : hs) {
			System.out.println(founder);
		}

		// deleting particular element
		hs.remove("Shiv Nadar");
		System.out.println("\n\nHashSet size after deleting : " 
				+ hs.size());

		// Iterating using enhanced for-loop
		System.out.println("\nAfter deleting particular object\n");
		for(String founder : hs) {
			System.out.println(founder);
		}

		// deleting all elements
		hs.clear();
		System.out.println("\n\nHashSet size after clearing : " 
				+ hs.size());

		// Iterating using enhanced for-loop
		System.out.println("\nIterating after clearing \n" + hs);
	}
}

Output:

Size of an HashSet is : 6

Iterating HashSet using enhanced for-loop

null
Shantanu Narayen
Francisco D’Souza
Shiv Nadar
Satya Nadella
Sundar Pichai


HashSet size after deleting : 5

Iterating after deleting particular object

null
Shantanu Narayen
Francisco D’Souza
Satya Nadella
Sundar Pichai


HashSet size after clearing : 0

Iterating after clearing 
[]

From above example, HashSet

  • doesn’t allow duplicate elements
  • maximum of one null object is allowed
  • while iterating, retrieve elements in random order

 

References:

 

Happy Coding !!
Happy Learning !!

retainAll() method explanation with HashSet
How to get size or length of HashSet