# Ultimate Cheat Sheet for Java Collections

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:**

```java
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:**

```java
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:**

```java
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:**

```java
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:**

```java
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:**

```java
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:**

```java
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:**

```java
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:**

```java
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**

| **Type** | **Best For** | **Allows Duplicates?** | **Sorted?** | **Fastest For?** |
| --- | --- | --- | --- | --- |
| `ArrayList` | Random access | ✅ Yes | ❌ No | Fast retrieval |
| `LinkedList` | Insertions/deletions | ✅ Yes | ❌ No | Fast modifications |
| `HashSet` | Unique elements | ❌ No | ❌ No | Fast lookups |
| `TreeSet` | Sorted unique elements | ❌ No | ✅ Yes | Ordered retrieval |
| `HashMap` | Key-value pairs | ❌ Keys unique | ❌ No | Fast key-value lookup |
| `TreeMap` | Sorted key-value pairs | ❌ Keys unique | ✅ Yes | Sorted key retrieval |
| `Queue` | FIFO operations | ✅ Yes | ❌ No | First-in-first-out processing |
| `Stack` | LIFO operations | ✅ Yes | ❌ No | Last-in-first-out processing |

---

### **🤩 Bonus Table – Similar Methods Across Collections**

| **Method** | **ArrayList** | **LinkedList** | **HashSet** | **TreeSet** | **HashMap** | **TreeMap** |
| --- | --- | --- | --- | --- | --- | --- |
| `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!** 🎯
