How to Choose the Right Collection in Java (Cheat Sheet)

Illustration for How to Choose the Right Collection in Java (Cheat Sheet)
By Last updated:

Choosing the right data structure in Java can dramatically impact your program’s performance, readability, and scalability. Java offers a robust set of collection types—List, Set, Queue, Map, and more—each tailored for specific scenarios.

This cheat sheet will guide you through the most commonly used Java collections, highlighting their differences, use cases, performance characteristics, and best practices. Whether you’re designing an algorithm, building APIs, or scaling backend services—this guide is your go-to reference.


🧱 Core Collection Categories at a Glance

Type Key Interface Key Classes Allows Duplicates Maintains Order Key Usage
List List ArrayList, LinkedList Ordered data, indexed access
Set Set HashSet, TreeSet TreeSet ✅ Unique elements only
Queue Queue PriorityQueue, ArrayDeque FIFO or priority-based processing
Map Map HashMap, TreeMap Keys ❌, Values ✅ TreeMap ✅ Key–value mapping, fast lookups

📘 When to Use What: Decision Table

Scenario Use This
Need ordered, duplicate-allowed list ArrayList
Want fast lookup by key HashMap
Require natural sorting TreeSet / TreeMap
Want insertion order maintained LinkedHashMap / LinkedHashSet
Require thread-safe list CopyOnWriteArrayList
Need FIFO queue ArrayDeque
Unique elements, unordered HashSet
Unique elements, sorted TreeSet

🔧 Java Syntax Snapshots

List

List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");

Set

Set<String> set = new HashSet<>();
set.add("One");
set.add("One"); // Ignored

Map

Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("A", 2); // Overwrites

⚙️ Internal Working Insights

  • ArrayList: Dynamic array; resizing when capacity exceeds
  • LinkedList: Doubly linked nodes
  • HashSet/HashMap: Hash table with buckets (uses hashCode() and equals())
  • TreeMap/TreeSet: Red-Black Tree for sorted access
  • PriorityQueue: Min-heap for element ordering by priority

🚀 Performance Comparison (Big-O)

Operation ArrayList HashSet TreeSet HashMap TreeMap
Add O(1)* O(1)* O(log n) O(1)* O(log n)
Search O(n) O(1) O(log n) O(1) O(log n)
Delete O(n) O(1) O(log n) O(1) O(log n)

* Amortized complexity due to resizing or hashing


✅ Best Practices for Choosing Collections

  • Prefer interfaces (List, Map) over implementation (ArrayList, HashMap)
  • Use Collections.unmodifiableList() or Java 9+ List.of() for immutability
  • Don’t use Vector, Hashtable, or legacy types
  • Match collection with access pattern (read-heavy vs write-heavy)
  • Consider memory vs speed trade-offs (e.g., TreeMap vs HashMap)

💡 Java 8+ Functional Enhancements

List<String> list = Arrays.asList("apple", "banana");
list.stream().filter(s -> s.startsWith("a")).forEach(System.out::println);
  • Use Collectors.toSet(), toMap() for functional transformations
  • Use Optional, Predicate, Function for cleaner code

📌 What's New in Java?

Java 8

  • Streams API
  • Lambdas, Predicate, Function, Optional

Java 9

  • List.of(), Set.of(), Map.of() factory methods
  • Immutable collections support

Java 10+

  • var for type inference
  • Performance tuning for G1 GC and other collections

Java 21

  • Structured concurrency (threads + collections)
  • Sequenced collections (preserves insertion order)

🧼 Refactoring Tip Sheet

Before:

List<String> list = new ArrayList<>();
for (String s : data) {
    if (!list.contains(s)) list.add(s);
}

After:

Set<String> set = new HashSet<>(data);

Cleaner, faster, and more intention-revealing.


📘 Conclusion and Key Takeaways

  • Choosing the right collection affects performance and clarity.
  • Know your use case: ordering, uniqueness, indexing, frequency of reads/writes.
  • Use interfaces and prefer immutability when possible.
  • Leverage Java 8+ APIs for powerful and expressive data handling.

❓ FAQ – Java Collection Selection

  1. What’s the fastest way to look up elements by key?
    Use HashMap (O(1) average time).

  2. Which collection maintains insertion order?
    LinkedHashMap, LinkedHashSet, ArrayList.

  3. How to make a collection immutable?
    Use Collections.unmodifiableX() or List.of() (Java 9+).

  4. What’s the difference between TreeMap and HashMap?
    TreeMap is sorted and slower; HashMap is faster but unordered.

  5. Can a Set have null values?
    HashSet allows one null. TreeSet does not (unless custom comparator).

  6. Why not use Vector or Hashtable?
    They're legacy, thread-safe but slower. Prefer ArrayList and ConcurrentHashMap.

  7. Is ArrayList thread-safe?
    No. Use CopyOnWriteArrayList or synchronized wrapper.

  8. Can I store duplicate keys in Map?
    No. A key is unique. Value is replaced if key already exists.

  9. Which Set preserves order?
    LinkedHashSet.

  10. When should I use TreeSet or TreeMap?
    When you need sorted elements or keys.