Collections · 312 words · 2 minute read
Choosing Java Collections: List, Set, Map, Queue, and Deque
By Priyanshu Rauth · Published 2026-09-04 · Updated 2026-09-04
The best Java collection is chosen by the questions your program needs to answer. Need ordered values with duplicates? Start with a List. Need membership or uniqueness? Use a Set. Need to associate a key with a value? Use a Map. Queue and Deque describe access order rather than a particular implementation, so code against those interfaces when possible.
Match the operation to the structure
ArrayList is an excellent default for indexed reads and append-heavy lists. HashSet gives expected constant-time membership but no meaningful iteration order. LinkedHashSet adds insertion order. TreeMap and TreeSet keep keys sorted at logarithmic cost. A HashMap is ideal for frequency counts and complement lookup.
import java.util.LinkedHashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Integer> unique = new LinkedHashSet<>();
unique.add(3); unique.add(1); unique.add(3); unique.add(2);
System.out.println(unique);
}
}The output is [3, 1, 2]: the duplicate is removed and the first-occurrence order remains. Replacing this with HashSet would keep uniqueness but not promise that display order.
Complexity is a guide, not a substitute for contracts
Hash-based expected O(1) operations rely on correct equals and hashCode for custom keys. Trees require comparable keys or a Comparator. An ArrayList removal from the middle shifts later elements, even though its indexed read is fast. State whether output order, duplicate multiplicity, and null values matter before committing to a type.
Common mistakes
- Depending on HashMap iteration order for user-visible output.
- Calling
Arrays.asListand expecting a growable list. - Changing a collection during for-each iteration instead of using an iterator.
- Using a Set when the number of duplicate occurrences matters.
Practice next
Use remove duplicates from a list to compare HashSet and LinkedHashSet. Then solve word frequency counter, list intersection, and sliding window maximum. The collections compiler page lets you swap implementations and observe which guarantees change.
Continue with the Java practice path · Try code in the Java compiler