Let’s learn difference between hashset and hashmap in java.
difference between hashset and hashmap
HashSet | HashMap |
We can store objects in HashSet. For example HashSet:{“Hello”, “World”} | In HashMap we can store key and value pairs. For example {1 ->”Hello”, 2 ->”World”} |
insertion order is not preserved. It is based on hashcode. | does not maintain insertion order. It is based on Hash function. |
has add() method. | has put() method. |
implements Set interface. | implements Map interface. |
do not allow duplicate elements. | allows duplicate values. Does not allow duplicate keys. |
allows single null value. | allows single null key and any number of null values. |
java hashmap example
import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<Integer, String>(); // add elements hm.put(10,"Apple"); hm.put(20,"Banana"); hm.put(30,"Cherry"); hm.put(40,"Dragonfruit"); // print HashMap elements System.out.println("HashMap elements: " + hm); // storing data with duplicate key hm.put(20, "Banana"); System.out.println("After inserting duplicate key: " + hm); } }
Output:
HashMap elements: {20=Banana, 40=Dragonfruit, 10=Apple, 30=Cherry}
After inserting duplicate key: {20=Banana, 40=Dragonfruit, 10=Apple, 30=Cherry}
java hashset example
import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { HashSet<String> hs = new HashSet<String>(); hs.add("Banana"); hs.add("Orange"); hs.add("Apple"); hs.add("Pineapple"); hs.add("Mango"); System.out.println("Before adding duplicate values: " + hs); // adding duplicate elements hs.add("Banana"); hs.add("Orange"); System.out.println("After adding duplicate values: " + hs); // adding null values hs.add(null); hs.add(null); // printing HashSet elements System.out.println("After adding null values: " + hs); } }
Output:
Before adding duplicate values: [Apple, Mango, Pineapple, Orange, Banana]
After adding duplicate values: [Apple, Mango, Pineapple, Orange, Banana]
After adding null values: [null, Apple, Mango, Pineapple, Orange, Banana]
Also read – encapsulation in java