Q: What is the difference between List, Set, and Map?

Answer:

These are the three core interfaces of the Java Collections Framework.

List — Ordered, Duplicates Allowed

An ordered collection (sequence). Elements are indexed by position and maintain insertion order. Duplicates are allowed.

List<String> list = new ArrayList<>();
list.add("Alice");
list.add("Bob");
list.add("Alice");  // ✅ Duplicates allowed
list.get(0);        // "Alice" — indexed access
// [Alice, Bob, Alice]
ImplementationBacked ByAccessInsert/DeleteUse Case
ArrayListDynamic arrayO(1) randomO(n) middleDefault choice, random access
LinkedListDoubly-linked listO(n)O(1) at head/tailFrequent insert/remove, queues
CopyOnWriteArrayListArray (copy on write)O(1)O(n) copiesMulti-threaded reads, rare writes

Set — No Duplicates

An unordered collection (by default) that does not allow duplicate elements.

Set<String> set = new HashSet<>();
set.add("Alice");
set.add("Bob");
set.add("Alice");  // ❌ Ignored — already exists
// [Bob, Alice] — no guaranteed order
ImplementationOrdered?Sorted?PerformanceUse Case
HashSetO(1) add/containsDefault choice
LinkedHashSet✅ Insertion orderO(1)When order matters
TreeSet✅ Sorted orderO(log n)Sorted, range queries

Map — Key-Value Pairs

Stores key-value pairs. Keys must be unique; values can be duplicated.

Map<String, Integer> map = new HashMap<>();
map.put("Alice", 90);
map.put("Bob", 85);
map.put("Alice", 95);  // Overwrites previous value for "Alice"
map.get("Alice");       // 95
ImplementationOrdered?Sorted?Thread-safe?Use Case
HashMapDefault choice
LinkedHashMap✅ Insertion orderLRU cache, ordered iteration
TreeMap✅ Sorted by keySorted keys, range queries
ConcurrentHashMapMulti-threaded access

Quick Decision Guide

Need indexed access?          → List (ArrayList)
Need uniqueness?              → Set (HashSet)
Need key-value lookup?        → Map (HashMap)
Need ordered + unique?        → LinkedHashSet or TreeSet
Need sorted + key-value?      → TreeMap
Need thread-safe map?         → ConcurrentHashMap