Skip to main content

Command Palette

Search for a command to run...

Ultimate Cheat Sheet for Java Collections

Updated
β€’6 min read
Ultimate Cheat Sheet for Java Collections
A

Hi πŸ‘‹ I’m Abhinav Prakash - a full-stack dev who loves building with Node.js, React, Next, Astro, MongoDB & Cloud. I share my blogs, learnings, side-projects, and dev journey here πŸš€

Ever felt lost in the jungle of Java Collections? Don't worry, I've got your back! This guide will take you through Lists, Sets, Maps, Queues, and Stacks with all their cool methods. Plus, you'll get a super handy table at the end! Let's roll. πŸ’ͺ


πŸ“Œ 1. List – Ordered & Duplicates Allowed

Think of a List as a VIP guest list at a party. Everyone comes in a specific order, and duplicates are totally fine. You can add, remove, and find elements at specific positions.

πŸ• ArrayList<E> – The Fast One

  • Best for: Fast random access, but slow insertions/removals.

  • Think of it as: A resizable array.

Common Methods:

ArrayList<String> list = new ArrayList<>();
list.add("A");          // Adds at the end
list.add(1, "B");       // Adds at index 1
list.get(0);            // Returns "A"
list.set(1, "C");       // Replaces "B" with "C"
list.remove(1);         // Removes index 1
list.contains("A");     // Returns true
list.indexOf("A");      // Returns index of "A"
list.lastIndexOf("A");  // Returns last occurrence of "A"
list.isEmpty();         // Returns true if empty
list.size();            // Returns size
list.clear();           // Removes all elements

πŸ›€ LinkedList<E> – The Smooth Operator

  • Best for: Fast insertions/deletions, but slow random access.

  • Think of it as: A train with connected compartments.

Common Methods:

LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(10);  
linkedList.addFirst(5);  // Adds at the beginning
linkedList.addLast(20);  // Adds at the end
linkedList.get(1);       // Returns element at index 1
linkedList.removeFirst(); // Removes first element
linkedList.removeLast();  // Removes last element
linkedList.peekFirst();   // Returns first element without removing
linkedList.peekLast();    // Returns last element without removing
linkedList.isEmpty();     // Returns true if empty
linkedList.size();        // Returns size

πŸ“Œ 2. Set – Unique Elements Only (No Duplicates Allowed!)

A Set is like your ex’s blocklistβ€”every name is unique, and order doesn't matter (except for TreeSet).

πŸ”₯ HashSet<E> – The Speed Demon

  • Best for: Super-fast searches.

  • Think of it as: A randomly ordered bag of unique elements.

Common Methods:

HashSet<String> set = new HashSet<>();
set.add("Java");       // Adds element
set.add("Python");
set.remove("Java");    // Removes "Java"
set.contains("Python"); // Returns true
set.isEmpty();         // Returns true if empty
set.size();            // Returns number of elements
set.clear();           // Removes all elements

🌲 TreeSet<E> – The Sorted Scholar

  • Best for: When you need elements in sorted order.

  • Think of it as: A self-sorting list.

Common Methods:

TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(10);
treeSet.add(5);
treeSet.add(20);
treeSet.first();     // Returns smallest element (5)
treeSet.last();      // Returns largest element (20)
treeSet.higher(10);  // First element greater than 10
treeSet.lower(10);   // First element smaller than 10
treeSet.remove(5);   // Removes 5

πŸ“Œ 3. Map – Key-Value Storage

A Map is like a real-life dictionaryβ€”you look up a key to find its value.

πŸ—Ί HashMap<K, V> – The Fast Look-up Boss

  • Best for: Fast key-value lookups, but unordered.

  • Think of it as: A messy but super-fast key-value storage.

Common Methods:

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");        // Adds key-value pair
map.put(2, "Two");
map.get(1);               // Returns "One"
map.remove(2);            // Removes key 2
map.containsKey(1);       // Returns true
map.containsValue("Two"); // Returns false (since we removed it)
map.keySet();             // Returns all keys
map.values();             // Returns all values
map.entrySet();           // Returns key-value pairs
map.getOrDefault(10, "Not Found");  // If key 10 not present, returns "Not Found"

🌳 TreeMap<K, V> – The Sorted Organizer

  • Best for: Keeping keys sorted.

  • Think of it as: A well-organized, auto-sorting dictionary.

Common Methods:

TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(3, "Three");
treeMap.put(1, "One");
treeMap.put(2, "Two");
treeMap.firstKey();   // Returns 1
treeMap.lastKey();    // Returns 3
treeMap.higherKey(2); // Returns 3 (next larger key)
treeMap.lowerKey(2);  // Returns 1 (previous smaller key)
treeMap.remove(1);    // Removes key 1
treeMap.getOrDefault(10, "Not Found");  // If key 10 not present, returns "Not Found"

πŸ“Œ 4. Queue & Stack – FIFO & LIFO Masters

🎟 Queue<E> – The Waiting Line

  • Best for: First-In-First-Out (FIFO) operations.

Common Methods:

Queue<String> queue = new LinkedList<>();
queue.add("A");   // Adds to queue
queue.poll();     // Removes and returns front element
queue.peek();     // Shows front element without removing
queue.size();     // Returns queue size

🎯 PriorityQueue<E> – The Smart Sorter

  • Best for: When you need automatic sorting while inserting elements.

  • Think of it as: A VIP entry systemβ€”smallest (or largest) element always gets out first!

Common Methods:

PriorityQueue<Integer> pq = new PriorityQueue<>(); // Min-Heap (Default)
pq.add(5);
pq.add(1);
pq.add(3);
pq.poll();    // Removes & returns the smallest element (1)
pq.peek();    // Shows the smallest element without removing (3)
pq.size();    // Returns size
pq.isEmpty(); // Checks if empty

// Max-Heap using Comparator
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.add(5);
maxHeap.add(1);
maxHeap.add(3);
maxHeap.poll(); // Removes & returns the largest element (5)

πŸ’‘ Default = Min-Heap (smallest comes out first). If you want a Max-Heap, use Collections.reverseOrder(). πŸš€

🧱 Stack<E> – The Last-Minute Cramming Machine

  • Best for: Last-In-First-Out (LIFO) operations.

Common Methods:

Stack<String> stack = new Stack<>();
stack.push("Book");   // Adds to stack
stack.pop();         // Removes and returns top element
stack.peek();        // Shows top element without removing
stack.size();        // Returns stack size

πŸ“Š Master Table – Java Collections at a Glance

TypeBest ForAllows Duplicates?Sorted?Fastest For?
ArrayListRandom accessβœ… Yes❌ NoFast retrieval
LinkedListInsertions/deletionsβœ… Yes❌ NoFast modifications
HashSetUnique elements❌ No❌ NoFast lookups
TreeSetSorted unique elements❌ Noβœ… YesOrdered retrieval
HashMapKey-value pairs❌ Keys unique❌ NoFast key-value lookup
TreeMapSorted key-value pairs❌ Keys uniqueβœ… YesSorted key retrieval
QueueFIFO operationsβœ… Yes❌ NoFirst-in-first-out processing
StackLIFO operationsβœ… Yes❌ NoLast-in-first-out processing

🀩 Bonus Table – Similar Methods Across Collections

MethodArrayListLinkedListHashSetTreeSetHashMapTreeMap
add()βœ…βœ…βœ…βœ…βœ… (put)βœ… (put)
remove()βœ…βœ…βœ…βœ…βœ…βœ…
contains()βœ…βœ…βœ…βœ…βœ… (containsKey)βœ… (containsKey)
size()βœ…βœ…βœ…βœ…βœ…βœ…
clear()βœ…βœ…βœ…βœ…βœ…βœ…

😎 Wrap-Up

And that's a wrap on Java Collections! πŸš€ Now, whether you're dealing with lists, sets, maps, queues, or stacks, you've got this handy cheat sheet to refer to anytime. Bookmark it, star it, share it! 🎯

More from this blog

A

Abhinav Prakash | Blogs

6 posts

I write about programming, AI, open-source tools, and my developer journey.
From building side projects to solving real-world dev problems