Difference between HashSet and HashMap in Java

In this post, we will see the difference between HashSet and HashMap in Java. First, we will see HashSet vs HashMap in brief later we will see each point in details.

HashSetHashMap
1.HashSet class implements Set interface and extends AbstractSet class.1.HashMap class implements Map interface and extends AbstractMap class
2.HashSet allows only values.It has add() method to add the elements.2.HashMap allows key and value pair.It has put() method to add the element.
3.HashSet doesn't allow duplicate value.3.HashMap doesn't allows duplicate key but value can be duplicate.
4.HashSet related to collection interface i.e HashSet implements Set interface and further Set interface extends Collection interface.4.But HashMap implements Map interface and map doesn't related to Collection interface.
5.HashSet internally uses HashMap only.5.HashMap uses Entry inner class(which is defined within HashMap class).

Let’s see all points in details.

HashSet class implements Set interface and extends AbstractSet class whereas HashMap class implements Map interface and extends AbstractMap class.

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {

}
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

}

 

HashSet allows only values. It has add() method to add the elements, HashMap allows key and value pair. It has put() method to add the element.

Example of HashSet –

import java.util.HashSet;
import java.util.Set;
 
public class HashSetExample {
	public static void main(String[] args) {
		Set<String> setObject = new HashSet<>();
 
		setObject.add("ram");
		setObject.add("mohan");
		setObject.add("shyam");
		setObject.add("mohan");
 
		// duplicates are not allowed but it will not give
		// any compilation error
		setObject.add("ram");
		System.out.println("set object -- " + setObject);
 
	}
}

Output is – set object — [shyam, mohan, ram]

Example of HashMap –

package treemapexp;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
class HashMapExample {
	public static void main(String[] arg) {
		Map<Integer, String> hashmapObject = new HashMap<>();
 
		hashmapObject.put(2, "ram");
		hashmapObject.put(3, "mohan");
		hashmapObject.put(4, "Bangalore");
		hashmapObject.put(5, "Rakesh");
 
		// we will iterate using Iterator
		Iterator<Map.Entry<Integer, String>> iterator = hashmapObject
				.entrySet().iterator();
 
		while (iterator.hasNext()) {
			Map.Entry<Integer, String> entry = iterator.next();
			System.out.println("Key is = " + entry.getKey() + ", Value is = "
					+ entry.getValue());
		}
	}
}

Output is –

Key is = 2, Value is = ram
Key is = 3, Value is = mohan
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh

 


You may like.