Java Map vs Set

In this post, I will be sharing what is the difference between Map and Set in Java with examples. Set and Map are the two interfaces that belong to the Java Collections framework. Let's dive deep into the topic:

Read Also: Convert Map to Set in Java

Java Map vs Set

1. Unique elements


Set contains unique elements i.e. it can not contain repeated values whereas Map can have the same value for different keys.

2. Iteration of elements


Iteration of Set elements can be done through forEach() or iterator() methods whereas Map elements cannot be iterated. To iterate the elements of Map, we need to convert Map into Collection using entrySet(), keySet(), or values() methods.

3. Collection interface


The Set interface extends the Collection interface whereas Map is a separate interface.

4. Null values


Set permits only one null value whereas Map allows a single null key at most and any number of null values.

Examples of Set and Map interfaces in Java

Set example


Below is an example of a Set:

 import java.util.Set;
import java.util.HashSet;

public class SetExample {
    public static void main(String args[]) 
    {
      // Creating HashSet object using Set
      Set<String> set = new HashSet<>();
      // Adding elements to the HashSet object
      set.add("dog");
      set.add("cat");
      set.add("cow");
      set.add("buffalo");
      // Printing HashSet object
      System.out.println(set);
    }
}


Output:
[cat, buffalo, cow, dog]

Map example


Below is an example of a Map:

 import java.util.Map;
import java.util.HashMap;

public class MapExample {
    public static void main(String args[]) 
    {
      // Creating HashMap object using Map
      Map<Integer, String> map = new HashMap<>();
      // Adding elements to the HashMap object
      map.put(1, "James");
      map.put(2, "Taylor");
      map.put(3, "John");
      map.put(4, "Leslee");
      // Printing HashMap object
      System.out.println(map);
    }
}


Output:
{1=James, 2=Taylor, 3=John, 4=Leslee}


Recap: Difference between Map and Set in Java


MapSet
Unique elementsUnique keys but repeated values are allowedYes, no repeated elements
Iteration of elementsUsing entrySet(), keySet() or values() methodsUsing forEach() or iterator() methods
Collection interfaceMap does not extends Collection interfaceSet extends Collection interface
Null valuesMap permits one null key and any number of null valuesSet permits one null value


That's all for today. Please mention in the comments if you have any questions related to the difference between Map and Set in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry