Choosing the Right Collection
Java has many collection classes, and choosing the right one makes code simpler and faster. The choice comes down to a few questions: Do you need key-value pairs? Are duplicates allowed? Does the order matter? Will several threads share it? In this lesson, you will learn a simple decision guide, see the best class for common situations, and finish this chapter with a summary of every collection covered.
Step 1: What Kind of Collection?
- Pairs of key and value? Use a Map.
- Only unique elements? Use a Set.
- Processing elements from the ends or by priority? Use a Deque or PriorityQueue.
- Otherwise, an ordered sequence with positions: use a List.
Step 2: Which Class?
| Need | Best choice |
|---|---|
| A general list | ArrayList |
| A queue (first in, first out) | ArrayDeque |
| A stack (last in, first out) | ArrayDeque |
| Always take the smallest or most urgent | PriorityQueue |
| Unique elements, order doesn't matter | HashSet |
| Unique elements in insertion order | LinkedHashSet |
| Unique elements, sorted, or nearest-value search | TreeSet |
| Unique enum values | EnumSet |
| Key-value lookup, order doesn't matter | HashMap |
| Key-value in insertion order, or an LRU cache | LinkedHashMap |
| Sorted keys, or nearest-key search | TreeMap |
| Enum keys | EnumMap |
| A fixed list of constants | List.of(...) |
| Shared map between threads | ConcurrentHashMap |
| Shared list, many reads, few writes | CopyOnWriteArrayList |
| Producer and consumer threads | ArrayBlockingQueue / LinkedBlockingQueue |
Example: One Problem, the Right Collections
Let's see an example: a library records which members borrowed which books, in order, and must quickly answer three questions.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class Library {
public static void main(String[] args) {
List<String[]> loans = new ArrayList<>();
loans.add(new String[] {"Navika", "Java Basics"});
loans.add(new String[] {"Srihitha", "SQL Guide"});
loans.add(new String[] {"Navika", "Data Structures"});
loans.add(new String[] {"Advitha", "Java Basics"});
Set<String> titles = new TreeSet<>();
Map<String, List<String>> byMember = new HashMap<>();
for (String[] loan : loans) {
titles.add(loan[1]);
byMember.computeIfAbsent(loan[0], k -> new ArrayList<>())
.add(loan[1]);
}
System.out.println("Loans in order: " + loans.size());
System.out.println("Distinct titles, sorted: " + titles);
System.out.println("Navika borrowed: " + byMember.get("Navika"));
}
}Loans in order: 4
Distinct titles, sorted: [Data Structures, Java Basics, SQL Guide]
Navika borrowed: [Java Basics, Data Structures]Explanation: The loans are a sequence where duplicates and order matter, so an ArrayList holds them. Distinct titles in sorted order call for a TreeSet. "Which books did this member borrow?" is a lookup by key, so a HashMap from member to a list of books answers it in one step.
Common Mistakes
Using a List and calling contains to prevent duplicates. Use a Set.
Using Stack, Vector or Hashtable in new code. Use ArrayDeque, ArrayList and HashMap or ConcurrentHashMap.
Using TreeMap "just in case" sorting is needed. It's slower; sort when you need to, or switch when sorting becomes frequent.
Interview Corner
How do you choose between List, Set and Map?
Use a Map when data is looked up by a key. Otherwise, use a Set when elements must be unique, and a List when duplicates are allowed and position or insertion order matters. Then pick the implementation by order requirements: hash-based (HashSet, HashMap) for no order, linked (LinkedHashSet, LinkedHashMap) for insertion order, tree-based (TreeSet, TreeMap) for sorted order. For shared data, use the concurrent versions.
Practice
- Easy: Choose a collection for each: the moves in a game so you can undo them; the unique visitors to a website; a dictionary of words and meanings shown alphabetically.
- Harder: Design the collections for a small online shop: products by ID, a cart that keeps the order items were added, the set of categories, and a queue of orders to ship. Write the declarations and explain each choice.
Key Takeaways
Was this tutorial helpful?