Pattern SplitAsStream And AsPredicate
Tokenize heterogeneous input lazily with splitAsStream and filter collections with Pattern.asPredicate instead of splitting whole strings into arrays.
Page 6 of 7
Tokenize heterogeneous input lazily with splitAsStream and filter collections with Pattern.asPredicate instead of splitting whole strings into arrays.
Build compound filters from small predicates with and, or, and negate, so each rule stays a one-line test that reads like the requirement.
Drain a PriorityBlockingQueue by priority: elements with the highest comparator order come out first, and take blocks while the queue is empty.
Read the JVM itself through ProcessHandle.current(): pid, command, start time, and child processes, with every detail wrapped in Optional.
Round-trip service configuration through Properties store and load, with getProperty's two-arg form supplying defaults for absent keys.
List built-in generator algorithms, select one by name, and prove same-seed reproducibility so tests and replays stay deterministic.
Bound lock waits with ReentrantLock.tryLock(timeout): give up instead of blocking forever while another thread holds the lock, unlocking only on success.
Match a repeated word with a backreference: \1 re-captures group one inside the pattern and $1 reuses it in replaceAll to collapse duplicates.
MULTILINE re-anchors ^ and $ per line, CASE_INSENSITIVE folds letter case, DOTALL lets dot cross newlines; flags combine with bitwise OR.
Greedy patterns grab to the last delimiter, reluctant ones stop at the first, and possessive ones never give back, so catastrophic backtracking cannot happen.
Validate several password rules with zero-width lookahead and slice dollar amounts with lookbehind, checking positions without consuming input characters.
Extract structured fields from log lines and email addresses with named capturing groups, reading each match by name instead of fragile numbered group indexes.
Point Scanner at any string or stream, swap its delimiter for a regex, and pull typed tokens with nextInt, which throws on non-numeric input.
Draw the same sample sequence on every run by seeding Random explicitly, the property test fixtures and example data need to be stable.
Use reversed(), getFirst, and getLast from the JDK 21 SequencedCollection interfaces so order-sensitive access no longer needs size-minus-one index arithmetic.
Walk the stack lazily for audit logs: filter frames to the nearest non-self caller, or read the direct caller class with RETAIN_CLASS_REFERENCE.
Reshape streams with JDK 24 Gatherers: windowFixed batches elements into fixed-size lists and fold reduces a stream to a single accumulated value.
Walk cursor-paginated APIs with the three-argument Stream.iterate, where the hasNext predicate ends the sequence exactly when the next token is null.
Fold a stream to one value three ways: with identity, as Optional without identity, and in parallel where the combiner merges partial sums.
Build case-insensitive key lookups with String.CASE_INSENSITIVE_ORDER: a TreeMap treats differently-cased duplicates as one key, so headers match any spelling.
Shift every line of a runtime-built multi-line string with indent, then recover messy indentation with stripIndent, which strips the smallest common indent.
String.split treats its argument as a regex: dots swallow whole strings, trailing empties vanish by default, and a negative limit is what preserves them.
subList hands back a live view: clearing it removes from the backing list, while structural edits to the backing list invalidate the view and throw.
Push readings through SubmissionPublisher, whose subscriber pulls items and exposes a future that completes only after everything is consumed.
Return values directly from switch expressions with arrow labels and yield, gaining exhaustive enum checking without default branches or fall-through.
Hand work straight from producer to consumer with a zero-capacity queue: put() blocks until another thread takes, so nothing is buffered in between.
Log through the JDK built-in System.Logger facade: zero dependencies, MessageFormat-style placeholders, and Supplier messages built only when the level is on.
Read built-in properties, supply defaults for absent keys, and mutate values at runtime — unlike environment variables, properties are writable.
TemporalAdjusters turns business rules like next Friday, last day of month, or first Monday into single with() calls on immutable LocalDate values.
Walk a thread through NEW, RUNNABLE, TIMED_WAITING, and TERMINATED with getState, the states thread dumps report for stuck workers.
Name pool threads through a ThreadFactory so thread dumps and logs identify workers: fixed pools spawn one named thread per task until core size.
Route exceptions escaping a raw thread to the default uncaught exception handler, and see why pooled submit() tasks keep theirs hidden inside the Future.
Encode every key and value with URLEncoder before joining the query string: form rules turn spaces into + and escape &, and URLDecoder reverses it.
Generate random UUIDv4 identifiers with randomUUID, parse canonical text back with fromString, and rely on fromString rejecting malformed input.
Give a plain field atomic operations through a VarHandle: compareAndSet fails on stale expectations and getAndAdd returns the value it replaced.
A volatile flag gives the worker loop a fresh read of shared state every iteration, so a writer thread stops it promptly instead of never.
Coordinate threads on one monitor with wait and notifyAll inside a synchronized guarded block that rechecks its condition in a while loop.
Delete a whole directory tree with Files.walkFileTree and a SimpleFileVisitor, clearing every file before each directory in postVisitDirectory.
Week boundaries differ by locale: WeekFields exposes the first day, minimal-days rule, and week numbering so calendar buckets match user expectations.
Validate card expiry printed as MM/yy with YearMonth.parse: the printed month stays valid through its last day, so only earlier months count as expired.
Open a zip archive as a filesystem with FileSystems.newFileSystem so Path APIs list and read entries without unpacking the archive first.
DST gaps shift forward with atZone and overlaps default to the earlier offset; withLaterOffsetAtOverlap pins the other side of a repeated wall-clock time.
Serve both LIFO and FIFO flows from one ArrayDeque: push/pop for undo stacks, offer/poll for queues, plus first/last access on both ends.
Do money math with BigDecimal instead of double: explicit setScale with RoundingMode, and compareTo instead of equals because scale makes 2.50 differ from 2.5.
Split text into words and sentences at locale-correct boundaries with BreakIterator, so apostrophes, decimals like 2.5, and abbreviations stay one token.
Encode the same string to UTF-8, UTF-16, and ISO-8859-1 and compare byte counts: UTF-8 roundtrips faithfully while unmappable chars degrade to ?.
Decode bytes that may be truncated UTF-8 with an explicit CharsetDecoder: REPORT rejects malformed input with an exception, REPLACE substitutes U+FFFD.
Encrypt sensitive fields with AES/GCM/NoPadding: a fresh 96-bit IV per message, a 128-bit auth tag on the ciphertext, and exceptions on tampering.
Compare strings the way users expect with a locale Collator; strength levels decide whether accents and case count as a difference when sorting.
Bound slow async calls with orTimeout and completeOnTimeout so a hung supplier resolves to a fallback value instead of blocking the caller forever.
Iterate a CopyOnWriteArrayList while updates land: the iterator holds an immutable snapshot, so concurrent modification never throws mid-loop.
Schedule retries with a DelayQueue: Delayed tasks become takeable only after their delay elapses, and the earliest deadline always leaves the queue first.
Guard a batch job against duplicate runs with FileChannel.tryLock: skip when another process holds the lock, release it when the run finishes.
Compare two files byte by byte with Files.mismatch: identical content yields -1, otherwise you get the offset of the first divergent byte, no manual loops.
Choose between Collections.unmodifiableList, a live view that follows the source list, and List.copyOf, a truly immutable snapshot that rejects all writes.
Rank work by severity with a PriorityQueue comparator: poll always yields the highest priority element, no matter the insertion order.
Compose fixed-width receipts and logs with printf specifiers: types, precision, width, alignment, grouping, signs, zero padding, and radices.
Stop a long-running worker with Thread.interrupt: the loop checks isInterrupted, the blocking sleep throws InterruptedException, and the flag gets restored.
Draw bounded random numbers without a shared seed using ThreadLocalRandom.current(), so concurrent tasks never contend on one Random instance.
Pack entries into an archive with ZipOutputStream and read names plus recorded sizes back through ZipFile, closing each entry before the zip is finished.
Read a file through AsynchronousFileChannel with a CompletionHandler callback; the calling thread is never blocked waiting on the disk read to finish.
Model permission flags as a BitSet and combine sets with and, or, andNot, then walk set bits with nextSetBit instead of looping over every index.
Drain finished tasks in completion order with ExecutorCompletionService take(), so slow submissions never delay already-finished results.
List directory entries through DirectoryStream glob patterns, sorting results yourself because entry order is unspecified by the JDK.
Meet another thread at an Exchanger and trade objects in one atomic handoff — exchange() blocks until both sides arrive, then returns the partner object.
Read a file in fixed-size chunks with FileChannel.read, flipping the ByteBuffer between write and read modes instead of loading the whole file.
Split an array range recursively and fork one half so ForkJoinPool threads compute partial sums in parallel, then join the halves into the total.
Bound a cache with LinkedHashMap in access order: get refreshes recency and removeEldestEntry evicts the least recently used key once capacity is exceeded.
Maintain a hot counter across threads with LongAdder, which splits contention across cells and exposes sum() once aggregation finishes.
Coordinate multi-phase group progression with Phaser: register workers on the fly, wait for every party each round, and deregister finishers.
Coordinate producer and consumer threads with one ReentrantLock and two Conditions so put blocks when the buffer is full and take blocks when empty.
Generate session tokens from SecureRandom bytes and render them with HexFormat, keeping 256 bits of entropy and predictable output formatting.
Take an optimistic snapshot with tryOptimisticRead and validate the stamp; fall back to a real read lock only when a write interfered mid-read.
Normalize user text with strip, stripLeading, stripTrailing, and isBlank, and build separators with repeat — strip handles Unicode spaces trim misses.
Assemble delimited output with StringJoiner: prefix and suffix framing, an explicit empty value, and merge that reuses the first joiner's delimiter.
Give each thread its own counter via ThreadLocal.withInitial so mutable per-thread state needs no locking; clear it before pooled threads get reused.
Answer threshold pricing with floorEntry plus ceilingKey, floorKey, and the headMap and tailMap range views on a key-sorted TreeMap.
Normalize Unicode text with Normalizer before comparing: composed e-acute and e plus combining accent are byte-identical in NFD but differ in raw length.
Compare arrays lexicographically with compare, locate the first difference with mismatch, and binarySearch a sorted array for exact or insertion points.
Encode and decode payloads with Base64's basic, URL-safe, and MIME encoders, including withoutPadding and the 76-character MIME line limit.
Move a ByteBuffer between write and read mode with flip, drain with get, and preserve unread bytes with compact instead of reallocating.
Validate text length by code points instead of chars: codePointCount counts one emoji as one, and codePoints().limit clips without corrupting surrogates.
Gate startup on several one-shot signals with CountDownLatch and await(timeout), so boot either proceeds when all dependencies report ready or aborts.
Synchronize phased work with a reusable CyclicBarrier: workers await at the barrier each round and the last arrival runs the barrier action.
Hash strings with MessageDigest SHA-256, render bytes with HexFormat, and compare digests with constant-time MessageDigest.isEqual.
Resolve user-controlled paths against a base directory, normalize away dot segments, and reject results that escape the base with startsWith.
Cap concurrent work with a counting Semaphore: tryAcquire rejects overflow immediately and release frees the slot in a finally block.
Slice ordered data from infinite Stream.iterate sources with takeWhile, dropWhile, and limit, each stopping or skipping at defined conditions.
Split text into a stream of lines, strip whitespace, and drop blank lines with lines(), strip(), and isBlank() instead of manual splitting.
Watch a directory for ENTRY_CREATE, ENTRY_MODIFY, and ENTRY_DELETE with WatchService, polling keys with a timeout and resetting them after each drain.
Track concurrent metrics with AtomicLong and LongAdder, and drive a compare-and-set loop when the update depends on the previous value.
Coordinate producer and consumer threads through an ArrayBlockingQueue with a poison-pill sentinel so shutdown is deterministic and lossless.
Expose a fluent builder over an immutable record that validates invariants once at build time so invalid instances cannot exist.
Split a stream into two buckets with partitioningBy and roll up grouped statistics with groupingBy plus downstream counting and averaging collectors.
Build a multi-field sort with Comparator.comparing thenComparing and nullsLast so secondary and tertiary orderings stay declarative.
Aggregate concurrent increments with ConcurrentHashMap compute and merge so counter updates stay atomic without external locking.
Replace switch chains with enum constants carrying behavior and an EnumMap registry so new strategies are one constant away.
Traverse a directory tree with Files.walk inside try-with-resources, filter by extension, and aggregate per-extension file counts and sizes.
Apply producer extends consumer super bounds to generic methods so a single helper reads from and fills any compatible list.
Send asynchronous HTTP requests with java.net.http.HttpClient, apply per-request timeouts, and chain response handling with CompletableFuture.