HashSet Vs HashMap in Java

As the names imply, a HashMap is an associative Map and HashSet is just a Set . But they are entirely different constructs. A HashMap is an implementation of Map interface. A Map interface maps keys to values. The key look up occurs using the hash. On the other hand, a HashSet is an implementation of Set interface. A Set is designed to match the mathematical model of a set. A HashSet does use a HashMap to back its implementation, as you noted. However, it implements an entirely different interface. HashMap is used to store key-value pairs using put method Example: hm.put(key, value); while HashSet is used to store only unique objects using add method Example: hs.add(object);. HashMap doesn't allow duplicate keys but values can be duplicated while HashSet doesn't allow duplicate objects HashMap allows maximum of one null key but any number of NULL values allowed while HashSet allows maximum of one null object to be added HashSet internally uses HashMap. So, there shouldn't be any performance difference whatsoever if you use them for the same purpose.

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()); } } }
Monday Thursday Friday Sunday Wednesday Tuesday Saturday

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())); } } }
How to create an Excel Document Programmatically Output
Key :1 Value :Sunday Key :2 Value :Monday Key :3 Value :Tuesday Key :4 Value :Wednesday