Enum ValueOf Lookup With Unknown Input
Parse user-supplied tokens into enum constants with valueOf, trim and uppercase the input, and fail with the full list of valid constants.
Page 4 of 7
Parse user-supplied tokens into enum constants with valueOf, trim and uppercase the input, and fail with the full list of valid constants.
Pull values out of delimited log fields with indexOf and substring instead of regex, and return null for missing keys so callers decide what absence means.
Detect upload MIME types with Files.probeContentType and treat the null result as unknown, since the mapping comes from the system file-type table.
Wrap a Callable in FutureTask so the expensive work runs exactly once even when several threads block on get, and later callers reuse the cached result.
Send a blocking HTTP request with HttpClient.send and inspect status code, headers, and body length, the sync counterpart to the async chaining API.
Integer.decode reads 0x and # prefixes as hex and a leading 0 as octal, while parseInt accepts an explicit radix from 2 to 36 for everything else.
Escape a string for embedding in JSON: quotes, backslashes, and control characters become the two-character or \uXXXX forms the spec requires.
Lambdas may only capture locals that are never reassigned: the compiler rejects captured variables that change, so mutable state flows through containers.
Walk an ArrayList forward with next() and backward with previous() from the same cursor, and replace elements in place via set() during iteration.
Validate card-style numbers with the Luhn checksum: double every second digit from the right and require the total to be divisible by ten.
Count occurrences in one pass with Map.merge: the remapping function runs only when the key is already present, so a fresh key needs no null check.
Mask card numbers, emails, and phone numbers with repeat and substring so logs keep the shape of a value without exposing the sensitive parts.
Sort versioned names like backup-10 after backup-9 by comparing digit runs numerically instead of lexicographically with a Character.isDigit scan.
Objects.checkIndex and checkFromToIndex return their argument when bounds hold and throw IndexOutOfBoundsException with a precise message when they do not.
Tighten a secret file to owner read/write with PosixFilePermissions, probing filesystem support first so non-POSIX systems degrade cleanly.
Serve localized messages from code-only ListResourceBundle subclasses: getBundle resolves by locale and default-locale fallback stays disabled.
Turn arbitrary titles into URL-safe slugs: NFD normalization folds accented letters, then runs of non-alphanumerics collapse into single dashes.
Probe a TCP service with Socket connect timeout and setSoTimeout so a dead peer cannot hang the caller, using a local ServerSocket as the responder.
anyMatch, allMatch, and noneMatch stop consuming the stream at the first decisive element, and an empty stream answers true for all and none, false for any.
Edit text in place with StringBuilder insert, reverse, delete, and replace instead of building new String copies per concatenation step.
Stop a worker with a bounded Thread.join timeout, then escalate to interrupt and join again so shutdown cannot hang on a blocked thread.
Prune large subtrees during Files.walkFileTree by returning SKIP_SUBTREE from preVisitDirectory, so dependency caches and hidden files never enter the walk.
Break text into lines no wider than the limit with a greedy pass: fill each line with as many words as fit, then start the next line.
Parse an XML payload into a DOM tree with a hardened DocumentBuilderFactory that rejects DOCTYPE declarations, then read elements and attributes.
Extract uploaded archives safely: resolve every entry against the target directory, normalize it, and reject any path that escapes the folder.
Copy, pad, slice, and fill primitive arrays with Arrays.copyOf, copyOfRange, and fill, keeping ranges half-open and copies independent.
Update volatile long fields without AtomicLong objects through AtomicLongFieldUpdater, using compareAndSet and incrementAndGet.
Track a value and a mark bit together with AtomicMarkableReference, testing compareAndSet and attemptMark transitions.
Test primality with BigInteger.isProbablePrime and walk to the next prime, clarifying what the certainty argument does and does not promise.
Wrap InputStream and OutputStream as channels with java.nio.channels.Channels, then copy bytes through a shared ByteBuffer.
Register a cleanup action with java.lang.ref.Cleaner, call Cleanable.clean explicitly, and show that repeat calls stay idempotent.
Rotate, reverse, shuffle, and count frequencies in lists with the Collections utilities while keeping seeded shuffles reproducible.
Concatenate stream elements with Collectors.joining, adding delimiters, prefixes, suffixes, and mapping each element to text in one terminal operation.
Fold stream elements with Collectors.reducing in its identity, mapped, and Optional forms, including an empty-stream fallback.
Sort records whose keys may be null by wrapping inner comparators with nullsFirst or nullsLast, keeping null handling out of business code.
Select currencies by ISO code or locale, then format amounts with the right symbol, grouping, and default fraction digits.
Send and receive UDP datagrams through DatagramChannel over loopback, showing connectionless addressing and byte buffer reuse.
Compress payloads with Deflater and restore them with Inflater, checking byte counts, zlib headers, and a lossless round trip.
Build a lazy thread-safe singleton with volatile and double-checked locking, where the second check inside the synchronized block prevents duplicate builds.
Accumulate double samples with DoubleAdder, read sumThenReset, and compare the running total with doubleValue after many adds.
Derive a shared secret with javax.crypto.KeyAgreement over EC keys and verify that both sides compute identical bytes.
Generate an EC key pair, sign a message with SHA256withECDSA, and verify it with the public key while rejecting a tampered payload.
Unwrap checked failures from concurrent tasks with ExecutionException.getCause, restoring the original exception instead of wrapping it in another layer.
Take over serialization with Externalizable, writing only the fields you choose in writeExternal and restoring them in readExternal.
Read and write whole text files in one call with Files.readString and writeString, choosing UTF-8 explicitly for predictable encoding.
Create a per-run scratch directory with Files.createTempDirectory, write working files inside it, and clean everything up recursively on shutdown.
Use Stream gather with Gatherers.scan to emit a running total after every element, including a custom String prefix accumulator.
Parse Set-Cookie style headers with HttpCookie.parse, read attributes, then rebuild a Cookie request header from a small jar.
Read a small payload into memory with readAllBytes, then stream it between streams with transferTo instead of hand-rolled buffer loops.
Store a generated AES key in a PKCS12 KeyStore, write it to disk, reload it with the same password, and compare key material.
Read text with LineNumberReader, set line numbers before parsing, and use mark and reset to reparse a section with correct numbering.
Generate a date stream with LocalDate datesUntil, step it by weeks, and confirm the end date is excluded from the result.
Aggregate a concurrent maximum with LongAccumulator while a LongAdder collects totals, then reset both without locking.
Carry key-value pairs through pipelines with the immutable Map.entry factory, whose instances reject setValue and slot into collectors without a map.
Control BigDecimal division precision with MathContext and rounding modes so non-terminating results never throw unexpectedly.
Inspect heap and non-heap memory through MemoryMXBean, printing used, committed, and maximum bytes around an allocation.
Look up virtual and static methods with MethodHandles, adapt signatures, and bind arguments before invoking them with invokeExact.
Encode with Base64.getMimeEncoder so long payloads wrap at a fixed width, then decode the wrapped text back to the original bytes.
Enumerate NetworkInterface instances, read hardware addresses and MTU, and filter usable IPv4 addresses excluding loopback.
Format a number with a locale and parse the result back through the same locale, so the roundtrip restores the value and mismatched locales truncate it.
Insert Thread.onSpinWait into a bounded spin loop so the CPU gets a hint that the thread is waiting on a flag rather than doing work.
Read host details from the OperatingSystemMXBean: name, arch, processors, and a load average that may be unavailable as -1.
Flatten a list of Optional values with Optional.stream so empty slots vanish from the pipeline without any explicit isPresent check.
Derive password hashes with PBKDF2WithHmacSHA256, a per-user random salt, and a high iteration count, then compare digests in constant time.
Use java.time.Period for calendar-based spans across months and years, where adding two months means something different every time.
Move bytes between threads through a NIO Pipe, using a dedicated writer thread and an EOF read loop instead of a shared buffer.
Seek to fixed offsets in a RandomAccessFile to read records, append at the end, and overwrite fields in place.
Inspect a record through getRecordComponents, invoke each accessor reflectively, and sum the values returned by the components.
Create and read arrays of unknown component type through java.lang.reflect.Array, including primitive arrays and type-checked writes.
Concatenate streams with SequenceInputStream, first as a pair and then through an enumeration, and read the joined bytes in order.
Accept one loopback client with ServerSocket, echo a line back through the socket streams, and close both ends with try-with-resources.
Register JVM shutdown hooks with Runtime.addShutdownHook, verify they can be removed, and use them for final flush or cleanup on normal exit.
Generate reproducible random sequences with SplittableRandom and split independent child generators for parallel tasks.
Join two streams with Stream.concat, then confirm the result stays lazy by counting side effects before the terminal operation runs.
Create bounded sequences with Stream.generate plus limit, and verify that no supplier call happens before a terminal operation.
Split text with StringTokenizer, including the returnDelims mode that keeps separators as tokens, and contrast it with String.split.
Wrap a list with Collections.synchronizedList, iterate under an explicit lock, and contrast it with an unsynchronized ArrayList.
Query sorted TreeSet subsets with headSet, tailSet, and subSet, then find floor, ceiling, and polled extremes in log time.
Read URI components, resolve relative references, and normalize dot segments without string concatenation or manual path parsing.
Derive a version 3 UUID with nameUUIDFromBytes, check its version and variant, and contrast it with a random version 4 UUID.
Write two entries with ZipOutputStream, then stream them back through ZipInputStream and read each entry before advancing.
Process text files line by line with the NIO Files API, streaming through map and filter without loading the whole file into memory.
Replace null-check ladders on Maps with getOrDefault, computeIfAbsent, and merge so lookup logic reads as one declarative call.
Get value equality for free with records and dispatch on their shape with pattern-matching switch — no getters or equals boilerplate.
Use IntStream and mapToInt to skip boxing entirely, then convert back with boxed when object streams need the values.
Round-trip delimited data with String.join, split, and StringJoiner so serialization stays consistent on both ends.
Rewrite lastModifiedTime and lastAccessTime explicitly through the attribute view so archival copies keep the original timestamps.
Count per-character occurrences by turning a String into an IntStream of chars and grouping into a sorted frequency map.
Pick one of several message forms by numeric range with ChoiceFormat, so 1 file, 2 files, and 0 files render grammatically correct text.
Measure spans between temporal values with ChronoUnit.between, choosing units from days down to nanos and watching truncation toward zero.
Wrap a downstream collector with collectingAndThen so grouped results finish as unmodifiable lists instead of mutable ArrayList defaults.
Fan out calls with CompletableFuture.supplyAsync, synchronize with allOf, then collect every result in order with the allOf-join trick.
Race several async sources with CompletableFuture.anyOf: the first to complete wins, the returned Object result needs one cast back.
Schedule a delayed stage with CompletableFuture.delayedExecutor (Java 9+): supplyAsync holds the stage back, orTimeout bounds the wait without Thread.sleep.
Adapt a custom index-range source to the Stream API by implementing tryAdvance, trySplit, estimateSize, and characteristics on a small Spliterator.
Accept both full and abbreviated timestamps by combining optional pattern sections with parseDefaulting for fields the input omits.
Render weekday and month names per locale with ofPattern().withLocale() and getDisplayName, where TextStyle chooses full, short, or narrow.
Key maps by enum constants with EnumMap: an array-backed implementation whose iteration always follows enum declaration order, unlike HashMap.
Check file identity before acting on it: read the owner UserPrincipal without following symlinks, then decide whether the sensitive read may proceed.
Resolve whether two paths denote one file with Files.isSameFile: it follows symlinks, so a link and its target compare equal while copies do not.