Using HashSet in Java. (Collection -5)

HashSet actually uses the HashMap to create a collection of objects. But it doesn’t have any key concepts like HashMap. It creates a list of items ignoring duplicate entries.

More on HashSet.
  • Class: HashSet
  • Interface: Set
  • Package: java.util

Features of HashSet

  • Duplicates elements are not allowed in Sets.
  • Only one ‘null’ value is allowed as it doesn’t support duplicate values.
  • Indexing of elements in Set classes not available like Lists.
  • Very fast to search for any specific item(element) in the set.
  • HashSet is not ordered in nature.
  • TreeSet remains sorted in the natural order in ascending order either it is integer or string.
  • TreeSet uses the tree algorithm internally.
  • LinkedHashSet, elements remain in the order they added.
  • LinkedHashSet uses LinkedList internally to process the data.

HashSet Supports all the methods for basic operations as mentioned below:

  1. To add items in a set use add(object).
  2. To get the size of the set use size(). It will return the number of items after removing all the duplicate entries.
  3. Traversing using foreach loop and iterator method is possible with HashSets.
  4. To remove any element use based on value or values we can use remove(object) or removeAll(collectionObject) method.
  5. Search any value we can use contains(object) or containsAll(collectionObject) methods.
  6. To remove all the entries from the set use clear() method.

HashSet Declaration

// Declaration of HashSet
		HashSet<String> hashSet=new HashSet<String>();
                HashSet<Integer> hashSet=new HashSet<Integer>();
                HashSet set3=new HashSet<>();

Adding values to HashSet using add(object)

// Declaration of HashSet
		HashSet<String> hashSet=new HashSet<String>();
		
		// Adding values to HashSet variable
		hashSet.add("Computer");
		hashSet.add("Laptop");
		hashSet.add("Charger");
		hashSet.add("UPS");
		hashSet.add("Laptop");
		hashSet.add("Keyboard");
		hashSet.add("Mouse");
		hashSet.add("Charger");
		hashSet.add(null);
		hashSet.add("Computer");
		hashSet.add("TouchPad");
		hashSet.add("Desktop");
		
		HashSet<Integer> set1=new HashSet<Integer>();
		set1.add(3);
		set1.add(1);
		set1.add(6);

Get Size of the set

// Returns size of set after removing duplicate entries.
		System.out.println("Size of HashSet after removing duplicates: "+hashSet.size());

Output:
Size of HashSet after removing duplicates: 9

Traversing the elements using foreach loop

// Declaration of HashSet
		HashSet<String> hashSet=new HashSet<String>();
		
		// Adding values to HashSet variable
		hashSet.add("Computer");
		hashSet.add("Laptop");
		hashSet.add("Charger");
		hashSet.add("UPS");
		hashSet.add("Laptop");
		hashSet.add("Keyboard");
		hashSet.add("Mouse");
		hashSet.add("Charger");
		hashSet.add(null);
		hashSet.add("Computer");
		hashSet.add("TouchPad");
		hashSet.add("Desktop");
System.out.println("\nTraversing of HashSet using foreach loop."); 
		for (String currentValue : hashSet) {
			
			System.out.println(currentValue);
			
		}

Output:
Traversing of HashSet using foreach loop.
null
Laptop
Mouse
Desktop
TouchPad
Keyboard
Computer
UPS
Charger

Traversing the elements using Iterator

System.out.println("\nTraversing of HashSet using Iterator");
		Iterator iterator=hashSet.iterator();
		
		while(iterator.hasNext())
		{
			System.out.println(iterator.next());
		}
Output:
Traversing of HashSet using Iterator
null
Laptop
Mouse
Desktop
TouchPad
Keyboard
Computer
UPS
Charger

Searching values using contains or containsAll methods

System.out.println("\nSearching a value in HashSet");
		System.out.println("Desktop is present in HashSet: "+ hashSet.contains("Desktop"));
		System.out.println("CPU is present in HashSet: "+hashSet.contains("CPU"));
		
		System.out.println("\nSearching all items from other list.");
		HashSet set3=new HashSet<>();
		set3.add("Charger");
		set3.add(3);
		set3.add(true);
		set3.add("Keyboard");
System.out.println("Result: "+hashSet.containsAll(set3));

Output:
Searching a value in HashSet
Desktop is present in HashSet: true
CPU is present in HashSet: false

Searching all items from other list.
Result: false

Using remove() or removeAll() methods

  • remove(object): This method removes a single element from the HashSet based on the value of the element.
  • removeAll(collectionObject): This method removes all the elements based on the elements present in another collection object.
System.out.println("\nRemove value from HashSet");
		// It removes all the duplicate values from the Set.
		hashSet.remove("Laptop");
		System.out.println(hashSet);
		
		System.out.println("\nRemove values based on other collection obeject.");	
                HashSet set3=new HashSet<>();
		set3.add("Charger");
		set3.add(3);
		set3.add(true);
		set3.add("Keyboard");	
		hashSet.removeAll(set3);
		System.out.println(hashSet);

Output:
Remove value from HashSet
[null, Mouse, Desktop, TouchPad, Keyboard, Computer, UPS, Charger]

Remove values based on other collection obeject.
[null, Mouse, Desktop, TouchPad, Computer, UPS]

clear() to remove all the elements

In the above example, we have seen that remove() eliminates elements from the list based on value. And we can remove only one element at a time using this method.

On the other hand, clear() method is used to remove all the elements from the current list irrespective to element values.

// Declaration of HashSet
		HashSet<String> hashSet=new HashSet<String>();
		
		// Adding values to HashSet variable
		hashSet.add("Computer");
		hashSet.add("Laptop");
		hashSet.add("Charger");
		hashSet.add("UPS");
		hashSet.add("Laptop");
		hashSet.add("Keyboard");
		hashSet.add("Mouse");
		hashSet.add("Charger");
		hashSet.add(null);
		hashSet.add("Computer");
		hashSet.add("TouchPad");
		hashSet.add("Desktop");
System.out.println("\nOriginal elements in set variable:\n"+hashSet);
		
		hashSet.clear();
		System.out.println("After removing all elements:\n"+hashSet);

Output:
Original elements in set variable:
[null, Mouse, Desktop, TouchPad, Computer, UPS]
After removing all elements:
[]

TestNG:

Computer Basics:

Java Basics:
Java Collection:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:

Selenium Tutorials:

JIRA:

Agile:


Leave a Comment

Your email address will not be published. Required fields are marked *

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.