Difference between Set and Map
Sets
Sets in Java represent a collection of unique elements. They do not allow duplicate elements, and they do not maintain any specific order of elements. Sets are primarily used when you need to store a collection of distinct values without caring about their order or frequency.
Maps
Maps in Java represent a collection of key-value pairs. Each key in a map must be unique, and it is associated with exactly one value. Maps do not maintain any specific order of key-value pairs. They are useful when you need to store and retrieve values based on some unique identifier or key.
Table of Contents
Now, let’s provide Set and Map Java code examples to illustrate these concepts:
Set Example:
java
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
// Creating a set
Set<String> mySet = new HashSet<>();
// Adding elements to the set
mySet.add("Apple");
mySet.add("Banana");
mySet.add("Orange");
mySet.add("Apple"); // Duplicate element, will be ignored
// Iterating through the set
System.out.println("Set elements:");
for (String fruit : mySet) {
System.out.println(fruit);
}
}
}
Map Example:
java
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// Creating a map
Map<Integer, String> myMap = new HashMap<>();
// Adding key-value pairs to the map
myMap.put(1, "Apple");
myMap.put(2, "Banana");
myMap.put(3, "Orange");
// Accessing value by key
System.out.println("Value associated with key 2: " + myMap.get(2));
// Iterating through the map
System.out.println("Map elements:");
for (Map.Entry<Integer, String> entry : myMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
In the set example, Set and Map we create a HashSet, which is a type of set, and add some elements to it. Notice that when we try to add a duplicate element (“Apple”), it is ignored because sets do not allow duplicates.
In the map example, we create a HashMap, which is a type of map, and add some key-value pairs to it. We can then access values using their corresponding keys. Maps are useful when you need to associate unique keys with specific values.