The snippet library.
Small, practical examples. Search by task or narrow things down below.
Find set members missing from another set
Java: Use removeAll on a copy to calculate a set difference.
Java✓ Tested
Find shared set members
Java: Copy a set before retainAll when the original must remain unchanged.
Java✓ Tested
Initialize a map entry only when absent
Java: Use computeIfAbsent when creating a collection for a new key.
Java✓ Tested
Locate a value in a sorted array
Java: Use Arrays.binarySearch only after establishing ascending order.
Java✓ Tested
Preserve map insertion order
Java: Use LinkedHashMap when iteration should follow the order keys were first added.
Java✓ Tested
Remove collection items that satisfy a condition
Java: Use removeIf on a mutable collection to avoid changing it manually inside a for-each loop.
Java✓ Tested
Retrieve the smallest queued value first
Java: PriorityQueue poll removes the smallest value under the natural ordering.
Java✓ Tested
Take an immutable list snapshot
Java: List.copyOf protects the snapshot from later changes to the source list.
Java✓ Tested
Use a deque as a FIFO queue
Java: Add at the tail and remove at the head using ArrayDeque.
Java✓ Tested
Use a deque as a stack
Java: Use push and pop for last-in, first-out behavior.
Java✓ Tested