The snippet library.
Small, practical examples. Search by task or narrow things down below.
Transform an asynchronous result
Java: Chain thenApply and join a CompletableFuture to retrieve the completed value.
Java✓ Tested
Transform an optional value
Java: Use Optional.map and orElse to transform a possibly absent result.
Java✓ Tested
Transform each stream value
Java: Use map to turn each input into a corresponding output.
Java✓ Tested
Treat dynamic regex input as literal text
Java: Use Pattern.quote so metacharacters in a search term lose their special meaning.
Java✓ Tested
Trim surrounding whitespace
Remove leading and trailing whitespace from a Java string.
Java✓ Tested
Update a running count
Java: Change a variable after its initial value has been assigned.
Java✓ Tested
Update a shared counter atomically
Java: AtomicInteger provides an indivisible increment operation for a shared counter.
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
Use an optional fallback
Use Optional.orElse to provide a default for a missing Java value.
Java✓ Tested
Validate a complete identifier
Java: String.matches requires the regular expression to match the entire input.
Java✓ Tested
Validate a required argument
Java: Use requireNonNull with a useful message at an API boundary.
Java✓ Tested