HashSet and HashMap

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Difference between HashSet and HashMap class

in Java
The HashMap and HashSet in Java are the most popular Collection classes. Both are used for the data
structure. The following table describes the difference between HashMap and HashSet:

Basis HashMap HashSet


Java HashMap is a hash table
HashSet is a Set. It creates a collection that
Definition based implementation of Map
uses a hash table for storage.
interface.
HashMap implements Map, HashSet implements Set, Cloneable,
Implementation Cloneable, and Serializable Serializable, Iterable and Collection
interface es. interfaces.
In HashMap we store a key-value
Stores pair. It maintains the mapping of In HashSet, we store objects.
key and value.
It does not allow duplicate keys,
Duplicate values It does not allow duplicate values.
but duplicate values are allowed.
It can contain a single null key
Null values It can contain a single null value.
and multiple null values.
Method of HashMap uses the put() method to HashSet uses the add() method to add
insertion add the elements in the HashMap. elements in the HashSet.
HashSet is slower than HashMap because the
HashMap is faster/ than HashSet
member object is used for calculating
Performance because values are associated
hashcode value, which can be same for two
with a unique key.
objects.
The Number of Only one object is created during There are two objects created during put
objects the add operation. operation, one for key and one for value.
Storing HashMap internally uses hashing HashSet internally uses a HashMap object to
Mechanism to store objects. store objects.
Always prefer when we do not It is used when we need to maintain the
Uses
maintain the uniqueness. uniqueness of data.
{a->4, b->9, c->5} Where a, b, c
Example are keys and 4, 9, 5 are values {6, 43, 2, 90, 4} It denotes a set.
associated with key.
HashSet in C# eliminates duplicate strings or elements in an array.In C#, it is an optimized set
collection.
Let us see an example to remove duplicate strings using C# HashSet. Here, we have duplicate elements

Example
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
static void Main() {

string[] arr1 = {
"bus",
"truck",
"bus",
"car",
"truck"
};

Console.WriteLine(string.Join(",", arr1));

// HashSet
var h = new HashSet(arr1);
// eliminates duplicate words
string[] arr2 = h.ToArray();
Console.WriteLine(string.Join(",", arr2));
}
}

Output
bus,truck,bus,car,truck
bus,truck,car

To declare HashSet −
var h = new HashSet(arr1);

Now set it on the array to remove the duplicate words −


string[] arr2 = h.ToArray();

Source:

You might also like