The Java Collections Framework for beginners is the essential toolkit to store, search, and process groups of objects in Java. If you’re learning Java in school or college, mastering Lists, Sets, and Maps early will make everyday coding tasks simpler and cleaner. In this step-by-step Java Collections Framework tutorial for beginners, you’ll learn what it is, why it matters, how to pick the right type (List, Set, or Map), how to iterate over them, and the common mistakes to avoid. For more Java learning paths and basics, explore the CodDesire Java section.
What is the Java Collections Framework in simple terms?
The Java Collections Framework (JCF) is a standard set of interfaces and classes for working with groups of objects. You use interfaces (like List, Set, and Map) to describe behavior, and you pick implementations (like ArrayList, HashSet, LinkedHashMap) for performance and ordering needs. This separation helps you write flexible code that’s easy to change later.
- List: ordered collection, allows duplicates.
- Set: no duplicates; some sets are ordered.
- Map: key–value pairs; keys are unique. Note: Map is not a subtype of Collection.
Modern Java adds two big improvements that beginners should know:
- Sequenced collections (Java 21+): ordered Lists, Sets, and Maps share common first/last operations (like
getFirst(),addLast(), andreversed()). - Easy unmodifiable collections: use
List.of(),Set.of(),Map.of(), andcopyOf()to make read-only collections concisely.
- Program to interfaces (List, Set, Map) and swap implementations later (e.g., ArrayList ↔ LinkedList).
- Choose by need: order? no duplicates? key → value lookups?
- Map stands apart (not a subtype of
Collection). - Java 21+ adds sequenced operations:
getFirst(),addLast(),reversed(). - Create read-only data with
List.of(),Set.of(),Map.of(), andcopyOf().
Why do we use collections?
Compared to raw arrays, collections:
- Grow or shrink automatically.
- Offer powerful operations (search, remove, contains, sort, reverse, etc.).
- Have multiple implementations you can swap without changing most code.
- Support iteration with for-each loops and streams.
Java Collection vs Collections explained
- Collection: the root interface (for groups of elements). List and Set extend it.
- Collections: a utility class with static helper methods such as
Collections.sort(...),Collections.unmodifiableList(...), andCollections.synchronizedList(...).
Java List, Set, Map basics
List: ordered and allows duplicates
Use a List when order matters or duplicates are allowed. The most common implementation for beginners is ArrayList. From Java 21 onward, List is a SequencedCollection, so you can use getFirst(), getLast(), addFirst(), addLast(), and reversed() consistently.
class="cd-keyword cd-access">public class ListBasics {
class="cd-keyword cd-access">public static void main(String[] args) {
// A resizable list suitable for most cases
java.util.List<String> names = new java.util.ArrayList<>();
names.add("Asha");
names.add("Ben");
names.add("Asha"); // duplicates allowed
// Sequenced operations (Java 21+)
System.out.println("First: " + names.getFirst());
System.out.println("Last: " + names.getLast());
names.addFirst("Zoe");
names.addLast("Kai");
// Iterate
for (String n : names) {
System.out.println(n);
}
// Reversed view (changes reflect in original)
java.util.List<String> reversed = names.reversed();
System.out.println("Reversed first: " + reversed.getFirst());
}
}Set: unique elements
Use a Set to avoid duplicates. Choose:
- HashSet for uniqueness without a guaranteed order.
- LinkedHashSet for predictable insertion order (a SequencedSet).
- TreeSet for sorted order (by natural order or comparator).
class="cd-keyword cd-access">public class SetBasics {
class="cd-keyword cd-access">public static void main(String[] args) {
java.util.Set<String> codes = new java.util.LinkedHashSet<>(); // preserves insertion order
codes.add("IN");
codes.add("US");
codes.add("IN"); // duplicate ignored
System.out.println(codes.contains("US")); // true
// Iterate
for (String c : codes) {
System.out.println(c);
}
}
}Map: key–value pairs (not a Collection)
Use a Map to look up a value by a unique key. Popular choices:
- HashMap: fast lookups; iteration order is not predictable.
- LinkedHashMap: predictable iteration order (insertion order by default); a SequencedMap.
- TreeMap: sorted by key (natural order or comparator). With natural ordering, null keys are not allowed.
class="cd-keyword cd-access">public class MapBasics {
class="cd-keyword cd-access">public static void main(String[] args) {
java.util.Map<String, Integer> scores = new java.util.LinkedHashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 92);
scores.put("Alice", 90); // replaces previous value for key ___CDPHSTR3___
// Get a value by key
System.out.println("Alice: " + scores.get("Alice"));
// Iterate entries
for (java.util.Map.Entry<String, Integer> e : scores.entrySet()) {
System.out.println(e.getKey() + " - " + e.getValue());
}
// Sequenced operations (Java 21+)
System.out.println("First entry: " + scores.firstEntry());
System.out.println("Last entry: " + scores.lastEntry());
}
}Simple guide to choose List, Set or Map in Java
Default: HashMap. Need predictable order? LinkedHashMap. Need sorting by key? TreeMap.
• Yes ➜ List (default: ArrayList)
• No ➜ Set (don’t care order: HashSet | keep insertion order: LinkedHashSet | sorted: TreeSet)
List.of(), Set.of(), Map.of() or copyOf().
| Use this | When you need | Common beginner pick |
|---|---|---|
| List | Ordered elements, duplicates allowed, index-based access | ArrayList |
| Set | Unique elements with optional predictable order | HashSet (no order) or LinkedHashSet (insertion order) |
| Map | Key–value pairs and fast lookups by key | HashMap (no order) or LinkedHashMap (insertion order) |
ArrayList vs LinkedList for beginners
ArrayList stores elements in a dynamic array; LinkedList stores nodes linked together. For beginners, prefer ArrayList for most cases because random access by index is fast and memory layout is simple. LinkedList can be useful for frequent insertions/removals at the ends, but random access is slower.
| Feature | ArrayList | LinkedList |
|---|---|---|
| Get by index | Fast (O(1)) | Slow (O(n)) |
| Add/remove at end | Fast (amortized) | Fast |
| Add/remove in middle | Potentially slow (shift elements) | Faster for large lists if you have the node/iterator |
| Memory | Compact array | Extra node overhead |
class="cd-keyword cd-access">public class ArrayListVsLinkedList {
class="cd-keyword cd-access">public static void main(String[] args) {
java.util.List<Integer> a = new java.util.ArrayList<>();
java.util.List<Integer> l = new java.util.LinkedList<>();
for (int i = 0; i < 5; i++) {
a.add(i);
l.add(i);
}
System.out.println("ArrayList get(3): " + a.get(3));
System.out.println("LinkedList get(3): " + l.get(3)); // works but slower internally
}
}Creating unmodifiable collections the modern way
- Use
List.of(),Set.of(),Map.of()to create unmodifiable collections quickly. - Use
List.copyOf(),Set.copyOf(),Map.copyOf()to copy into unmodifiable variants. - Mutating these collections throws
UnsupportedOperationException. Also,of()methods reject nulls.
class="cd-keyword cd-access">public class UnmodifiableCollections {
class="cd-keyword cd-access">public static void main(String[] args) {
java.util.List<String> fixed = java.util.List.of("A", "B", "C");
System.out.println(fixed.size()); // 3
// fixed.add(___CDPHSTR3___); // UnsupportedOperationException
java.util.Map<String, Integer> m = java.util.Map.of("x", 1, "y", 2);
System.out.println(m.get("x"));
}
}How to iterate over a List, Set, and Map in Java
Iteration patterns are very similar. Use the for-each loop for readability; use an Iterator when you need to remove elements safely while iterating.
class="cd-keyword cd-access">public class IterationExamples {
class="cd-keyword cd-access">public static void main(String[] args) {
java.util.List<String> list = new java.util.ArrayList<>();
list.add("red"); list.add("green"); list.add("blue");
// For-each List
for (String color : list) {
System.out.println(color);
}
// Iterator with removal
java.util.Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().startsWith("g")) {
it.remove(); // safe removal
}
}
System.out.println(list);
// Set
java.util.Set<Integer> nums = new java.util.LinkedHashSet<>();
nums.add(2); nums.add(3); nums.add(2);
for (int n : nums) {
System.out.println(n);
}
// Map - entries
java.util.Map<String, Integer> map = new java.util.LinkedHashMap<>();
map.put("A", 1); map.put("B", 2);
for (java.util.Map.Entry<String, Integer> e : map.entrySet()) {
System.out.println(e.getKey() + "=>" + e.getValue());
}
}
}Thread-safety basics for students
- Single-threaded apps: use standard collections like
ArrayList,HashMap, etc. - Occasional multi-thread access:
Collections.synchronizedList(and similar) provide thread-safe single operations, but if you iterate, you must lock externally on the collection. - High concurrency: use concurrent collections such as
ConcurrentHashMap(note: it does not allow null keys or values).
- Do I need key → value lookups? If yes, pick a Map (HashMap / LinkedHashMap / TreeMap).
- Are duplicates allowed? If yes, use a List; if no, use a Set.
- Do I care about order? Choose LinkedHash* for insertion order or Tree* for sorting.
- Do I need first/last operations or reversed()? Prefer sequenced types (Java 21+).
- Should the collection be read-only? Use
of()/copyOf()or unmodifiable collectors. - Will multiple threads modify it? Consider
Collections.synchronizedXxxorConcurrentHashMap. - Will elements be used as keys or in a HashSet? Implement
equalsandhashCodecorrectly. - Any null values? Remember many modern factories (
of()) and some maps/sets disallow nulls.
Common mistakes with Java collections for beginners
- Expecting HashMap or HashSet to keep insertion order. If you need predictable order, pick LinkedHashMap or LinkedHashSet.
- Confusing Collection (interface) with Collections (utility class).
- Modifying a collection while iterating with for-each, causing
ConcurrentModificationException. Use anIteratoranditerator.remove(). - Forgetting to implement
equals/hashCodefor custom types used in HashSet or as Map keys, leading to duplicate or missing lookups. - Using Stack or Vector in new code. Prefer Deque (e.g.,
ArrayDeque) for stacks/queues. - Assuming unmodifiable means immutable data.
List.of()prevents structural changes, but if elements are mutable objects, their internal state can still change.
Practical example: Java ArrayList and HashMap examples for students
class="cd-keyword cd-access">public class StudentDirectory {
class="cd-keyword cd-access">public static void main(String[] args) {
// ArrayList: preserve order of IDs entered
java.util.List<Integer> ids = new java.util.ArrayList<>();
ids.add(101); ids.add(104); ids.add(101); // duplicate allowed
System.out.println("IDs: " + ids);
// HashMap: map ID -> name (order not guaranteed)
java.util.Map<Integer, String> directory = new java.util.HashMap<>();
directory.put(101, "Asha");
directory.put(104, "Ben");
directory.put(101, "Asha Sharma"); // replaces earlier value
System.out.println("Name for 101: " + directory.get(101));
System.out.println("Contains 999? " + directory.containsKey(999));
// If you need predictable order, switch to LinkedHashMap
java.util.Map<Integer, String> ordered = new java.util.LinkedHashMap<>(directory);
System.out.println("Ordered keys: " + ordered.keySet());
}
}Quick tips for Java 21+ learners
- Prefer ordered implementations that support sequenced operations when you care about first/last (e.g.,
LinkedHashMap,LinkedHashSet, and allListtypes). - Use
reversed()on sequenced collections to traverse from the end without copying. - Build read-only data quickly with
of()andcopyOf(); use collectors likeCollectors.toUnmodifiableList()with streams.
FAQ: People also ask
What is the Java Collections Framework in simple terms?
It’s a standard library of interfaces and classes that help you store and work with groups of objects—like lists of names, sets of unique IDs, and maps from IDs to students—using consistent APIs.
Which should I use in Java: List, Set, or Map?
- Use List when you need an ordered collection that can contain duplicates.
- Use Set when you need to prevent duplicates; use LinkedHashSet if you also need predictable order.
- Use Map when you need to associate keys with values and look them up efficiently.
What is the difference between Collection and Collections in Java?
Collection is an interface for groups of elements. Collections is a utility class that provides static helper methods such as sorting, creating synchronized wrappers, and making unmodifiable views.
How is ArrayList different from LinkedList for beginners?
ArrayList is usually the default choice: it’s fast for random access and appending. LinkedList can be better for frequent insertions/removals at the ends but is slower for getting elements by index.
How do I iterate over a List or Map in Java?
Use a for-each loop for readability, or iterate with an Iterator when you need safe removal. For maps, iterate through entrySet() to access both keys and values.


