1. Set in Java
A Set
is a collection that doesn’t allow duplicate elements. It’s ideal when you want to store unique items.
Common Types of Sets:
HashSet
(no order)LinkedHashSet
(insertion order)TreeSet
(sorted order)
import java.util.HashSet;
public class SetExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // Duplicate, won't be added
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Output might be:
Banana
Apple
Orange
Note: HashSet
doesn’t maintain order.
✅ When to Use a Set
Use a Set
when:
- You only care about unique values, not duplicates.
- You don’t need to associate elements with keys (i.e., just a list of items).
- Order doesn’t matter—or you want a specific order like sorted or insertion order.
Example Use Cases:
- Storing unique email addresses.
- Tracking visited web pages.
- Managing a list of tags or categories.
Performance Tip:
HashSet
offers constant-time performance for basic operations likeadd()
,remove()
, andcontains()
, assuming a good hash function.
2. Map in Java
A Map
stores key-value pairs. Each key must be unique, but values can be duplicated.
Common Types of Maps:
HashMap
(no order)LinkedHashMap
(insertion order)TreeMap
(sorted by keys)
Example using HashMap
:
import java.util.HashMap;
public class MapExample {
public static void main(String[] args) {
HashMap<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Alice");
studentMap.put(102, "Bob");
studentMap.put(103, "Charlie");
studentMap.put(101, "David"); // Key 101 updated to David
for (Integer id : studentMap.keySet()) {
System.out.println("ID: " + id + ", Name: " + studentMap.get(id));
}
}
}
Output might be:
ID: 101, Name: David
ID: 102, Name: Bob
ID: 103, Name: Charlie
✅ When to Use a Set
Use a Set
when:
- You only care about unique values, not duplicates.
- You don’t need to associate elements with keys (i.e., just a list of items).
- Order doesn’t matter—or you want a specific order like sorted or insertion order.
Example Use Cases:
- Storing unique email addresses.
- Tracking visited web pages.
- Managing a list of tags or categories.
Performance Tip:
HashSet
offers constant-time performance for basic operations likeadd()
,remove()
, andcontains()
, assuming a good hash function.
✅ When to Use a Map
Use a Map
when:
- You need to associate a key with a value (like a dictionary).
- Keys must be unique, but values can repeat.
- Fast lookups based on keys are needed.
Example Use Cases:
- Storing user information with user ID as key.
- Word counts where word is key and count is value.
- Caching with quick access by key.
Performance Tip:
HashMap
is usually very fast forget()
andput()
operations (again, assuming a well-distributed hash function).