Java Examples

Page 5 of 7

Browse Java examples

javaSnippet

Files Lines Lazy Large Log Scan

Scan a multi-gigabyte log line by line with Files.lines: lazy streaming, filtered early, and closed by try-with-resources without loading the file.

javaSnippet

Optional ifPresentOrElse Branch

Handle both branches of an Optional in one call with ifPresentOrElse: the value action and the empty action live side by side, no if-get wrapping.

javaSnippet

Optional Or Fallback Chain

Build lazy fallbacks with Optional.or: each supplier runs only when the previous chain stage is empty, unlike eager orElse arguments.

javaSnippet

WeakHashMap Key Life Cycle

Store metadata beside objects with WeakHashMap: entries vanish once keys are garbage collected, so caches do not leak strong references.

javaSnippet

CompletableFuture Callback Bridge

Complete a hand-built CompletableFuture from a legacy callback thread so listener APIs join async pipelines; late duplicate callbacks cannot rewrite the result.

javaSnippet

EnumSet Compact Constant Set

Model fixed option sets with EnumSet: noneOf, of, range, and complementOf build bit-packed sets of enum constants that iterate in declaration order.

javaSnippet

Executor InvokeAny First Success

invokeAny races the same request across worker tasks, returns the first success, cancels the rest, and throws ExecutionException only when every task fails.

javaSnippet

Executor Rejection Policy Choices

See what a saturated ThreadPoolExecutor does with new tasks: AbortPolicy throws RejectedExecutionException, CallerRunsPolicy runs the task in the submitter.

javaSnippet

Lazy Supplier Memoized Value

Wrap an expensive initializer in a memoized Supplier so the value is computed on first get and reused afterwards without re-running the loader.