If you're developing in Java, you will inevitably work with List, Set, and Map. These core members of the Java Collections Framework provide powerful ways to store and manipulate groups of data.
But knowing which one to use and when is critical. Each collection type serves a different purpose—some allow duplicates, some maintain order, others are key-value pairs. Choosing the right one can significantly impact your program’s readability and performance.
📚 Definitions and Purpose
What is a List?
- Ordered collection that allows duplicates.
- Elements can be accessed by index.
- Backed by classes like
ArrayList
,LinkedList
.
What is a Set?
- Unordered collection with no duplicates.
- Backed by
HashSet
,TreeSet
,LinkedHashSet
.
What is a Map?
- Stores key–value pairs.
- Keys are unique, values can repeat.
- Implemented by
HashMap
,TreeMap
,LinkedHashMap
.
🧱 Syntax and Structure
List Example
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Allowed
Set Example
Set<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Red"); // Ignored
Map Example
Map<String, Integer> stock = new HashMap<>();
stock.put("Apple", 50);
stock.put("Banana", 100);
stock.put("Apple", 60); // Overwrites
⚙️ Internal Working
Type | Backed By | Handles Duplicates | Maintains Order | Access Style |
---|---|---|---|---|
List | ArrayList, LinkedList | Yes | Yes | By index |
Set | HashSet, TreeSet | No | TreeSet/LHSet: Yes | By iteration |
Map | HashMap, TreeMap | Keys: No, Values: Yes | Depends | By key |
🚀 Performance and Complexity
Operation | ArrayList | HashSet | HashMap |
---|---|---|---|
Insertion | O(1)* | O(1)* | O(1)* |
Lookup | O(1) | O(1) | O(1) |
Remove | O(n) | O(1) | O(1) |
Sorted Operations | O(n log n) | O(log n) | O(log n) |
* Amortized complexity
🔄 Real-World Use Cases
When to Use List
- Order matters (e.g., UI menus, search results)
- Allows duplicates (e.g., list of votes)
When to Use Set
- Unique values only (e.g., user emails)
- No concern about order (use
HashSet
) - Maintain order (use
LinkedHashSet
orTreeSet
)
When to Use Map
- Lookup by key (e.g., dictionary, ID to object mapping)
- Fast retrieval and update
- Store key-based configs or cache
💡 Java 8+ Functional Support
With List
fruits.stream().filter(f -> f.startsWith("A")).forEach(System.out::println);
With Set
Set<String> filtered = colors.stream().filter(c -> c.length() > 3).collect(Collectors.toSet());
With Map
stock.entrySet().stream()
.filter(e -> e.getValue() > 50)
.forEach(e -> System.out.println(e.getKey()));
❌ Anti-Patterns and Common Mistakes
- Using List for uniqueness: use Set instead
- Using Set when ordering matters: prefer List or LinkedHashSet
- Modifying Map while iterating without using
Iterator
- Choosing TreeSet/TreeMap without needing sort (they're slower)
🧼 Refactoring Example
Before:
List<String> usernames = new ArrayList<>();
for (String u : rawData) {
if (!usernames.contains(u)) {
usernames.add(u);
}
}
After:
Set<String> usernames = new HashSet<>(rawData);
✅ Best Practices
- Prefer interface types in declarations (
List
instead ofArrayList
) - Use
Collections.unmodifiableList()
if you don’t want mutation - Use
EnumSet
orEnumMap
for enums - Avoid
Vector
,Hashtable
unless absolutely needed
📌 What's New in Java?
Java 8
- Streams, lambda expressions
- Functional APIs for
List
,Set
,Map
Java 9
- Factory methods:
List.of()
,Set.of()
,Map.of()
Java 10+
var
type inference
Java 21
- Sequenced Collections (preview)
- Better support for immutable data pipelines
📘 Conclusion and Key Takeaways
- List: ordered, allows duplicates — use when order matters.
- Set: unordered or sorted, no duplicates — use for uniqueness.
- Map: key–value pairs — use for fast lookup and associations.
Choose the right type based on your data model and access patterns to write efficient, clear, and bug-free Java code.
❓ FAQ – List vs Set vs Map
-
Can a List have duplicate elements?
Yes, duplicates are allowed. -
What happens if I add duplicate to Set?
It is ignored — only unique elements are stored. -
Can a Map have duplicate keys?
No. A key can only appear once; it will overwrite. -
Which one maintains insertion order?
ArrayList
,LinkedHashSet
, andLinkedHashMap
. -
How do I get values from a Map?
Usingmap.get(key)
or by iterating overentrySet()
. -
Is Set faster than List?
For lookup and remove, yes (O(1) vs O(n)). -
Can I sort a Set?
Yes, by usingTreeSet
or sorting manually. -
Why does HashMap allow one null key?
It's an implementation choice. Only one null key is allowed, but many null values. -
How to make a collection unmodifiable?
UseCollections.unmodifiableList()
orList.of()
(Java 9+). -
Which one is thread-safe?
None by default. UseConcurrentHashMap
,CopyOnWriteArrayList
, or wrap withCollections.synchronizedX()
.