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
Map | Set | |
---|---|---|
Unique elements | Unique keys but repeated values are allowed | Yes, no repeated elements |
Iteration of elements | Using entrySet(), keySet() or values() methods | Using forEach() or iterator() methods |
Collection interface | Map does not extends Collection interface | Set extends Collection interface |
Null values | Map permits one null key and any number of null values | Set 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.