What is diffrence between HashSet and HashMap in java? Answer it with relevent code example.

Heera JatHeera Jat
2 min read

Table of contents

HashSet and HashMap are both data structures used in Java for storing and managing collections of elements, but they serve different purposes and have different characteristics:

  1. HashSet:

    • HashSet is a collection that stores unique elements. It does not allow duplicate values.

    • Elements in a HashSet are not ordered, meaning there is no specific order in which elements are stored or retrieved.

    • It is based on the concept of a hash table where elements are hashed, allowing for fast insertion, deletion, and retrieval operations.

Example code for HashSet:

    import java.util.HashSet;

    public class HashSetEx {
        public static void main(String[] args) {
            HashSet<String> names = new HashSet<>();

            // Adding elements to the HashSet
            names.add("Alice");
            names.add("Bob");
            names.add("Charlie");
            names.add("Alice"); // Duplicate won't be added

            // Iterating through the HashSet
            for (String name : names) {
                System.out.println(name);
            }
        }
    }

Output:

    Charlie
    Bob
    Alice
  1. HashMap:

    • HashMap is a collection that stores key-value pairs. It allows for efficient retrieval of values based on their associated keys.

    • Keys in a HashMap must be unique, but values can be duplicates.

    • HashMap does not guarantee any specific order of elements.

Example code for HashMap:

    import java.util.HashMap;

    public class HashMapEx {
        public static void main(String[] args) {
            HashMap<Integer, String> studentMap = new HashMap<>();

            // Adding key-value pairs to the HashMap
            studentMap.put(1, "Alice");
            studentMap.put(2, "Bob");
            studentMap.put(3, "Charlie");
            studentMap.put(4, "Alice"); // Duplicate value with different key

            // Retrieving values from the HashMap
            String name = studentMap.get(2);
            System.out.println("Student with ID 2 is: " + name);
        }
    }

Output:

    Student with ID 2 is: Bob

In summary, HashSet is used to store a collection of unique elements, while HashMap is used to store key-value pairs, where keys are unique. The choice between them depends on the specific requirements of your program. If you need to store and retrieve values based on keys, HashMap is suitable. If you simply need to store a set of unique elements, HashSet is the appropriate choice.

3
Subscribe to my newsletter

Read articles from Heera Jat directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Heera Jat
Heera Jat