HashSet Vs HashMap in Java

HashSet and HashMap are both classes that provide collection frameworks for storing and manipulating data. While they have similar names, they serve different purposes and have distinct characteristics.

HashSet

  1. HashSet is an implementation of the Set interface.
  2. It does not allow duplicate elements. If you attempt to add an element that already exists in the HashSet, it will not be added.
  3. Elements in a HashSet are not ordered. There is no guarantee on the order in which elements will be stored or retrieved.
  4. It uses hashing to store elements, which enables fast lookup and retrieval.
  5. HashSet is primarily used when you want to store a collection of unique elements and you do not require any specific ordering of the elements.

HashSet Implementation

import java.util.*; class TestClass { public static void main (String[] args) { //create a HashSet Object HashSet days=new HashSet(); // add elements to the HashSet days.add("Sunday"); days.add("Monday"); days.add("Tuesday"); days.add("Wednesday"); days.add("Thursday"); days.add("Friday"); days.add("Saturday"); //Iterate through HashSet Iterator itr=days.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }

Examples of use cases for HashSet include removing duplicates from a list, checking membership, or finding the intersection or difference between two sets.

Output
Monday Thursday Friday Sunday Wednesday Tuesday Saturday

HashMap

  1. HashMap is an implementation of the Map interface.
  2. It stores data in key-value pairs, where each key is unique.
  3. Elements in a HashMap are not ordered. The order of key-value pairs is not guaranteed.
  4. HashMap allows null values for both keys and values.
  5. It also uses hashing to store elements, allowing for efficient key-based retrieval.
  6. HashMap is commonly used when you need to associate values with unique keys and perform efficient lookups or updates based on those keys.

HashMap Implementation

import java.util.*; class TestClass { public static void main (String[] args) { //Create HashMap HashMap < Integer,String > days = new HashMap < Integer,String >(); //Add Key/Value pairs days.put(1,"Sunday"); days.put(2,"Monday"); days.put(3,"Tuesday"); days.put(4,"Wednesday"); Set < Map.Entry < Integer,String > > set = days.entrySet(); for (Map.Entry < Integer,String > sg : set) { System.out.println("Key :"+sg.getKey() + " Value :"+days.get(sg.getKey())); } } }

Examples of use cases for HashMap include caching values, indexing data, or implementing a dictionary.

Output
Key :1 Value :Sunday Key :2 Value :Monday Key :3 Value :Tuesday Key :4 Value :Wednesday

Conclusion

HashSet is used when you need a collection of unique elements without any specific ordering, while HashMap is used when you need to store key-value pairs with efficient lookup capabilities.