Java Cheatsheet

Collections

Use this Java reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Collections Overview

java.util hierarchy:

Collection
├── List          — ordered, allows duplicates
│   ├── ArrayList
│   ├── LinkedList
│   └── Vector / Stack (legacy)
├── Set           — no duplicates
│   ├── HashSet
│   ├── LinkedHashSet  (insertion-ordered)
│   └── TreeSet        (sorted)
└── Queue / Deque
    ├── ArrayDeque
    ├── PriorityQueue
    └── LinkedList

Map (not Collection)
├── HashMap
├── LinkedHashMap  (insertion-ordered)
├── TreeMap        (sorted by key)
└── Hashtable (legacy)

Immutable Factory Methods (Java 9+)

List<String>  list = List.of("a", "b", "c");           // immutable, no nulls
Set<Integer>  set  = Set.of(1, 2, 3);                  // immutable, no nulls, random order
Map<String,Integer> map = Map.of("a",1, "b",2);        // up to 10 pairs
Map<String,Integer> big = Map.ofEntries(               // unlimited
    Map.entry("a", 1),
    Map.entry("b", 2)
);

// Mutable copy from immutable
List<String> mutable = new ArrayList<>(List.of("a","b","c"));

List

ArrayList

import java.util.ArrayList;
import java.util.List;

List<String> list = new ArrayList<>();
list.add("Alice");                   // append
list.add(0, "Zara");                 // insert at index
list.addAll(List.of("Bob","Carol")); // add all

list.get(0)                          // "Zara"
list.set(0, "Yara")                  // replace at index, returns old
list.remove(0)                       // remove by index, returns element
list.remove("Bob")                   // remove first occurrence by value
list.size()                          // number of elements
list.isEmpty()                       // true if size == 0
list.contains("Alice")               // true/false
list.indexOf("Alice")                // first index, -1 if not found
list.lastIndexOf("Alice")
list.subList(1, 3)                   // view [1,3) — not a copy
list.clear()                         // remove all

// Sorting
Collections.sort(list);
list.sort(Comparator.naturalOrder());
list.sort(Comparator.reverseOrder());
list.sort(Comparator.comparing(String::length));

// Searching
Collections.binarySearch(list, "Bob");  // requires sorted
Collections.shuffle(list);
Collections.reverse(list);
Collections.frequency(list, "Alice");

// Convert
Object[] arr = list.toArray();
String[] strArr = list.toArray(String[]::new);   // Java 11+
String[] strArr2 = list.toArray(new String[0]);  // classic form

LinkedList (List + Deque)

LinkedList<String> ll = new LinkedList<>();
ll.addFirst("front");    ll.addLast("back");
ll.getFirst();           ll.getLast();
ll.removeFirst();        ll.removeLast();
ll.peekFirst();          ll.peekLast();   // null if empty (vs. exception)
// Use as Queue: offer/poll/peek; as Stack: push/pop/peek

Set

HashSet

Set<String> set = new HashSet<>();
set.add("apple");
set.add("apple");    // duplicate — ignored, returns false
set.remove("apple");
set.contains("banana");
set.size();

// Set operations
Set<Integer> a = new HashSet<>(Set.of(1,2,3,4));
Set<Integer> b = new HashSet<>(Set.of(3,4,5,6));
a.addAll(b);                  // union (modifies a)
a.retainAll(b);               // intersection (modifies a)
a.removeAll(b);               // difference (modifies a)

LinkedHashSet — insertion order preserved

Set<String> linked = new LinkedHashSet<>(List.of("b","a","c"));
// iteration order: b, a, c

TreeSet — sorted (natural or Comparator)

TreeSet<Integer> tree = new TreeSet<>();
tree.add(5); tree.add(1); tree.add(3);
tree.first()         // 1
tree.last()          // 5
tree.floor(4)        // 3  (largest ≤ 4)
tree.ceiling(4)      // 5  (smallest ≥ 4)
tree.lower(3)        // 1  (strictly <)
tree.higher(3)       // 5  (strictly >)
tree.headSet(4)      // [1, 3]  (< 4)
tree.tailSet(3)      // [3, 5]  (≥ 3)
tree.subSet(2, 5)    // [3]     ([2,5))
tree.pollFirst()     // removes and returns 1
tree.pollLast()      // removes and returns 5

Queue and Deque

PriorityQueue (min-heap by default)

PriorityQueue<Integer> pq = new PriorityQueue<>();
PriorityQueue<Integer> maxPq = new PriorityQueue<>(Comparator.reverseOrder());

pq.offer(3); pq.offer(1); pq.offer(2);
pq.peek()    // 1 (head, doesn't remove)
pq.poll()    // 1 (removes and returns head)
pq.size()
pq.isEmpty()

// Custom objects
PriorityQueue<int[]> pq2 = new PriorityQueue<>((a, b) -> a[0] - b[0]);

ArrayDeque (stack + queue, faster than LinkedList)

ArrayDeque<String> deque = new ArrayDeque<>();

// As Queue (FIFO)
deque.offer("first");    // add to tail
deque.poll();            // remove from head (null if empty)
deque.peek();            // head without remove

// As Stack (LIFO)
deque.push("top");       // add to head
deque.pop();             // remove from head (throws if empty)
deque.peek();

// Both ends
deque.offerFirst("a");   deque.offerLast("z");
deque.pollFirst();       deque.pollLast();
deque.peekFirst();       deque.peekLast();

Map

HashMap

Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);                         // insert/update
map.get("Alice")                              // 30, null if missing
map.getOrDefault("Bob", 0)                    // 0 if missing
map.containsKey("Alice")                      // true
map.containsValue(30)                         // true
map.remove("Alice")                           // removes entry, returns value
map.size()
map.isEmpty()

// Conditional updates (Java 8+)
map.putIfAbsent("Alice", 99)                  // only puts if key absent
map.computeIfAbsent("Bob", k -> k.length())  // compute and store if absent
map.computeIfPresent("Alice", (k,v) -> v+1)  // update only if present
map.compute("Alice", (k, v) -> v == null ? 1 : v + 1) // always

// Merge — useful for counting
map.merge("word", 1, Integer::sum);           // word_count++

// Replace
map.replace("Alice", 31);                    // only if key exists
map.replace("Alice", 30, 31);                // only if key maps to 30 (CAS)

// Iteration
for (Map.Entry<String,Integer> e : map.entrySet()) {
    System.out.println(e.getKey() + "=" + e.getValue());
}
map.forEach((k, v) -> System.out.println(k + "=" + v));
Set<String>  keys   = map.keySet();
Collection<Integer> vals = map.values();

// Bulk
map.putAll(otherMap);
map.clear();

LinkedHashMap — insertion order or access order

Map<String,Integer> lhm = new LinkedHashMap<>();  // insertion-ordered
// Access-ordered (useful for LRU cache):
Map<String,Integer> lru = new LinkedHashMap<>(16, 0.75f, true) {
    @Override protected boolean removeEldestEntry(Map.Entry<String,Integer> eldest) {
        return size() > 100;   // keep at most 100 entries
    }
};

TreeMap — sorted by key

TreeMap<String, Integer> tree = new TreeMap<>();
tree.firstKey();          tree.lastKey();
tree.floorKey("c");       tree.ceilingKey("c");
tree.lowerKey("c");       tree.higherKey("c");
tree.headMap("d");        // keys < "d"
tree.tailMap("d");        // keys >= "d"
tree.subMap("b","e");     // keys in ["b","e")
tree.descendingKeySet();  // reversed
tree.descendingMap();

Collections Utility Methods

import java.util.Collections;

Collections.sort(list)
Collections.sort(list, comparator)
Collections.reverse(list)
Collections.shuffle(list)
Collections.shuffle(list, new Random(42))
Collections.binarySearch(list, key)
Collections.binarySearch(list, key, comparator)
Collections.min(collection)
Collections.max(collection)
Collections.min(collection, comparator)
Collections.frequency(collection, obj)
Collections.disjoint(c1, c2)             // true if no common elements
Collections.swap(list, i, j)
Collections.fill(list, value)
Collections.copy(dest, src)              // dest must be ≥ src size
Collections.nCopies(3, "x")             // ["x","x","x"] (immutable)
Collections.singletonList("a")           // immutable 1-element list
Collections.emptyList()                  // immutable empty list
Collections.unmodifiableList(list)       // read-only view
Collections.synchronizedList(list)       // thread-safe wrapper
Collections.checkedList(list, String.class) // runtime type checking

Iteration Patterns

// for-each (preferred)
for (String s : list) { System.out.println(s); }

// Iterator (use when removing during iteration)
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.startsWith("A")) it.remove();  // safe removal
}

// ListIterator (bidirectional)
ListIterator<String> lit = list.listIterator(list.size());
while (lit.hasPrevious()) {
    System.out.println(lit.previous());
}

// removeIf (Java 8+)
list.removeIf(s -> s.isEmpty());

// replaceAll (Java 8+)
list.replaceAll(String::toUpperCase);

Conversion Between Collection Types

// List ↔ Set
List<String> list = new ArrayList<>(set);
Set<String>  set  = new HashSet<>(list);        // deduplicated
Set<String>  linked = new LinkedHashSet<>(list); // deduplicated, ordered

// Array ↔ List
List<String> fromArr = Arrays.asList("a","b","c");  // fixed-size, backed by array
List<String> mutable = new ArrayList<>(Arrays.asList("a","b","c"));
String[] arr = list.toArray(String[]::new);

// Stream → Collection
List<String> l = stream.collect(Collectors.toList());
List<String> l2 = stream.toList();                   // Java 16+, unmodifiable
Set<String>  s  = stream.collect(Collectors.toSet());
Map<K,V> m = stream.collect(Collectors.toMap(keyFn, valFn));

Concurrent Collections (java.util.concurrent)

ClassDescription
ConcurrentHashMapThread-safe HashMap; no null keys/values
CopyOnWriteArrayListThread-safe; copies on write — good for read-heavy
CopyOnWriteArraySetThread-safe Set based on CopyOnWriteArrayList
ConcurrentLinkedQueueLock-free FIFO queue
BlockingQueue (iface)LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue
Map<String, Integer> safe = new ConcurrentHashMap<>();
safe.putIfAbsent("key", 1);
safe.computeIfAbsent("key", k -> expensiveCompute(k));