The snippet library.
Small, practical examples. Search by task or narrow things down below.
Retrieve the smallest queued value first
Java: PriorityQueue poll removes the smallest value under the natural ordering.
Java✓ Tested
Return a value from a switch expression
Java: Use an exhaustive switch expression with a fallback for other input values.
Java✓ Tested
Round a decimal with an explicit rule
Java: Construct BigDecimal from text to avoid importing a binary floating-point approximation.
Java✓ Tested
Run a task on an executor and close it
Java: Java 21 ExecutorService supports try-with-resources to shut down after submitted work.
Java✓ Tested
Run cleanup after a handled exception
Java: A finally block executes whether the protected operation succeeds or fails.
Java✓ Tested
Run your first program
Java: Start with a complete program that prints one line. Follow the run instructions below.
Java✓ Tested
Sort a list
Sort a mutable Java list in natural ascending order.
Java✓ Tested
Split comma-separated text
Split a simple comma-separated string into individual Java values.
Java✓ Tested
Store a value in a named variable
Java: Give a value a descriptive name and print it.
Java✓ Tested
Sum integer values
Reduce a Java integer stream to its sum.
Java✓ Tested
Take a page from a stream
Java: Use skip and limit with a known stable input order.
Java✓ Tested
Take an immutable list snapshot
Java: List.copyOf protects the snapshot from later changes to the source list.
Java✓ Tested