Learn-dsa..in 30 days!



























HashSet Operations

Initializing the HashSet.

Below are some ways to initialize HashSets in java.

HashSet<String> strs= new HashSet<String>();
strs.add(“Invoice”);
strs.add(“Payment”);
strs.add(null);
HashSet<Integer> ints= new HashSet<Integer>();
ints.add(3);
Ints.add(7);

The HashSet add() method returns true if the input element is added to the HashSet and returns false if the element was duplicate.

HashSet class has around 4 constructors that can be used to create and initialize HashSets. These constructors take Collections or HashSet capacity and load factor as inputs. We can construct the HashSet using one of these constructors as needed.

The HashSet addAll() method takes a collection as an input and adds all elements of the collection to the HashSet. Duplicate values are not added

Size of the HashSet.

The size of the HashSet (number of elements in the HashSet) be accessed using the size() function as shown below:

int strsSize= strs.size();

Searching within a HashSet.

The HashSet contains() method can be used to search for element in the HashSet. The contains() method returns true if the element is found in the HashSet:

boolean check = strs.contains(“currency”);

The HashSet containsAll() method takes a collection as an input and returns true if all elements of the collection are part of the HashSet.

Accessing the HashSet's elements.

To access the HashSet’s elements, we need to use an iterator as shown below:

Iterator itr=strs.iterator();
while (itr.hasNext()) {
	System.out.println(itr.next());
}

Removing elements from the HashSet

We can remove elements from the HashSet using the HashSet remove() method. The remove() methods returns true if the element was found within the HashSet and removed.:

strs.remove(“Payment”);

The HashSet removeAll() method takes a collection as an input and removes the collection's elements from the HashSet.

LinkedHashSet and TreeSet classes.

In addition to HashSet class, Java also provides LinkedHashSet and TreeSet classes. LinkedHashSet class allows insertion order of elements to be preserved. LinkedHashSet is internally implemented as a doubly linked list. TreeSet Class allows added elements to be ordered as per their natural orders or as per provided comparator. TreeSet provides methods such as first(), last(), lower(), higher(), headset(), tailSet() to access various elements contained in the TreeSet.