The snippet library.
Small, practical examples. Search by task or narrow things down below.
Read the beginning of a text value
Java: Extract or display the first three ASCII characters from a known nonempty string.
Java✓ Tested
Read the first collection element
Java: Access index zero only after establishing that the collection is nonempty.
Java✓ Tested
Reject nonfinite floating-point values
Java: Double.isFinite excludes both infinity and NaN.
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
Remove duplicate values
Preserve encounter order while removing repeated Java list values.
Java✓ Tested
Repeat a fixed number of times
Java: Use a counted loop to print three numbered steps.
Java✓ Tested
Repeat text a fixed number of times
Java: Use String.repeat with a nonnegative repetition count.
Java✓ Tested
Repeat while a condition holds
Java: Count down while a positive number remains, updating the loop variable on each iteration.
Java✓ Tested
Replace literal text
Replace all literal matches in a Java string without regular expressions.
Java✓ Tested
Replace one collection element
Java: Update an existing element at a known valid index.
Java✓ Tested
Represent a finite set of states
Java: Use an enum to prevent arbitrary strings from representing application states.
Java✓ Tested
Require two conditions to be true
Java: Combine a lower and an upper bound to check whether a value is in range.
Java✓ Tested