HashSet vs HashMap in Java

In this post, we will learn the difference between HashSet and HashMap in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it. 

Difference between HashSet and HashMap in Java

Features HashSet HashMap
Interface Implements Set interface Implements Map interface
Data Storage Stores data as objects Stores data as key-value pairs
Internal Structure Uses HashMap internally Uses an array of Entry<K, V> objects internally
Duplicate Elements Doesn't allow duplicates Allows duplicate values but not duplicate keys
Null Elements Allows only one null element Allows one null key and multiple null values
Insertion Operation Requires one object Requires two objects - key and value
Performance Slightly slower than HashMap Slightly faster than HashSet

Example with HashSet:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Create a HashSet
        HashSet<String> hSet = new HashSet<>();

        // Add elements
        hSet.add("apple");
        hSet.add("banana");
        hSet.add("cherry");
        hSet.add("apple"); // Trying to add a duplicate

        // Display the HashSet
        System.out.println("HashSet:");
        for (String fruit : hSet) {
            System.out.println(fruit);
        }
    }
}

Output:

HashSet:
apple
banana
cherry

Example with HashMap:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> hMap = new HashMap<>();

        // Add elements (key-value pairs)
        hMap.put(1, "apple");
        hMap.put(2, "banana");
        hMap.put(3, "cherry");
        hMap.put(3, "date"); // Trying to use a duplicate key

        // Display the HashMap
        System.out.println("HashMap:");
        for (Integer key : hMap.keySet()) {
            System.out.println(key + " => " + hMap.get(key));
        }
    }
}

Output:

HashMap:
1 => apple
2 => banana
3 => date

Related Collections Interview QA

  1. map() vs flatMap() in Java
  2. Collections vs Streams
  3. ArrayList vs Vector
  4. Iterator vs ListIterator
  5. HashMap vs HashTable
  6. HashSet vs HashMap
  7. Array vs ArrayList
  8. Fail-Fast Iterators vs Fail-Safe Iterators
  9. HashMap vs ConcurrentHashMap
  10. LinkedList vs ArrayDeque
  11. LinkedList vs Array
  12. LinkedList vs Doubly LinkedList
  13. Enum vs EnumSet in Java
  14. HashMap vs. TreeMap in Java
  15. Synchronized Collections vs. Concurrent Collections

Comments