Reservoir Sampling:One Pass When You Do Not Know n Up Front
Keep the first k items, then for each later index i (1-based), replace a slot with probability k/i — a uniform sample of k from a stream of unknown length.
Read More194 post(s)
Keep the first k items, then for each later index i (1-based), replace a slot with probability k/i — a uniform sample of k from a stream of unknown length.
Read MoreSquare the base and consume the exponent bit by bit — O(log exp) multiplies instead of a loop of exp products, for integers or modular pow.
Read MoreFor i from n-1 down to 1, swap a[i] with a uniform index in 0..i — every permutation equally likely, which is what Collections.shuffle already runs.
Read MoreReplace repeated subtraction with remainder, then back-substitute for Bézout coefficients — gcd, lcm, and a modular inverse when gcd is 1.
Read Mored × w counters and the min over hashes: over-estimate frequencies on purpose when a HashMap of every key will not fit.
Read MoreA decision guide for the Java Collections series: given the hot operation, null policy, encounter order, and whether another thread looks — which JDK type to new.
Read MoreBuild a trie of all needles, add failure links like KMP on a forest, then scan the haystack once — every pattern that ends at the current character reports.
Read MoreEstimate cardinality with a handful of registers and a harmonic mean — plus-or-minus is the point, not a HashSet of every key.
Read MoreLearn how Java 21 sequenced collections provide uniform first, last, and reversed operations across lists, deques, ordered sets, and ordered maps.
Read MoreAlign the pattern at the window end, use a bad-character skip (and the good-suffix idea) so a late mismatch jumps the haystack instead of sliding by one.
Read MoreModel a tiny promo DSL as AND/OR of percent-off and sku-in-category expressions that evaluate(Order), and skip it when a few ifs or a real parser would be honest.
Read MoreRaft terms, leader election, and log replication at awareness depth — enough to know what etcd and Kafka-adjacent consensus are doing, not enough to ship your own cluster.
Read MoreAdd CSV export and tax walks to a stable Sku / Category tree with accept(Visitor) so each new report is a class, not another method on every catalog type.
Read MoreSlide a window hash in O(1), compare hashes first, then verify characters — the procedure for one needle or many needles against the same haystack.
Read MoreClone a configured DiscountPolicy, ChargeRequest, or gateway test double in Java instead of rebuilding constructor arguments — and skip clone() when new is cheaper or the copy shares mutable guts.
Read MoreA coordinator asks every participant to prepare, then commit or abort together — and why a crashed coordinator leaves the cluster stuck.
Read MoreUndo a checkout draft in Java by letting Order take an opaque snapshot — no public fields, no JSON dump, and no serializing OrderProcessor.
Read MoreStop DiscountPolicy, PaymentGateway, fraud, inventory, and the notifier from importing each other by letting CheckoutMediator own the checkout conversation.
Read MoreWait base × 2^attempt after a failure, cap the wait, and add jitter so retries do not stampede the same instant.
Read MoreShare immutable catalog SKU metadata across cart LineItems so a Black Friday order does not clone name, tax class, and image URL on every row.
Read MoreQueue work into a bucket that leaks at a constant rate — overflow is dropped or the caller waits. Smooth output, not a stored burst of tokens.
Read MoreStop the Email×SendGrid / SMS×Twilio subclass grid by letting OrderNotifier hold a MessageSender so channels and vendors vary independently.
Read MoreBuild the LPS prefix table, then scan the text once — on a mismatch the pattern jumps using already-matched prefix, so the text index never retreats.
Read MoreStop walking Order line items with get(i) on a leaked ArrayList so a switch from list to a SKU tree does not rewrite OrderProcessor.
Read MoreRefill tokens at a steady rate, spend one per request, and allow a burst up to bucket capacity — then reject or wait.
Read MoreBuild Stripe-region and Razorpay-region checkout families in Java so gateway, webhook parser, and money type vary together without OrderProcessor naming the concretes.
Read MoreGrow a min-heap of crossing edges from a seed until every vertex is in the tree — a Dijkstra-shaped frontier for an MST, not distances from a source.
Read MoreReplace a hard-coded fraud-inventory-payment-notify sequence with a Handler chain in Java so a new checkout step is a class you splice in, not a next-type you edit.
Read MorePlace keys on a ring so adding or removing a node remaps only its neighbors — not every key — with virtual nodes to even the load.
Read MoreReplace a growing DRAFT / PAID / REFUNDED / VOID switch in process, refund, and void with OrderStatus objects that own legal transitions, so OrderProcessor stops being the state machine.
Read MoreChoose, recurse, undo: search a decision tree with pruning when the next pick depends on the path — not a second knapsack table.
Read MoreReplace nested loops over Outdoor / Hiking / SKUs with a CatalogNode tree so a category and a single product both answer subtotal(), and OrderProcessor still charges one payable.
Read MorePut a PaymentGateway proxy in front of a slow SDK so OrderProcessor still calls charge, while lazy init, an auth check, and a last-result cache decide whether the real gateway runs.
Read MorePick a maximum subset of non-overlapping intervals by earliest finish time — greedy that throws ranges away, not merge-intervals.
Read MoreTurn charge, refund, and capture into Java objects you can queue, retry, undo, or audit — without wrapping a one-shot process() in ceremony.
Read MoreHide checkout’s discount, payment, fraud, and tax conversation behind one CheckoutFacade.place(Order) so controllers stop assembling the subsystem.
Read MoreTry JEP 532 in JDK 27: use primitive patterns with instanceof, switch directly on long, float, double, and boolean, and reject lossy conversions without hand-written casts.
Read MoreFind repeated phrases in a sliding window as length-distance pairs, then Huffman-code the tokens — that pairing is DEFLATE, not Huffman alone.
Read MoreFreeze a shared Java payment sequence so capture, refund, and void keep one skeleton and only the provider step (and hooks) vary.
Read MoreBuild a prefix-free code from symbol frequencies with a heap: greedy merges, why it is optimal here, and why this is not DEFLATE.
Read MoreKeep a process-wide resource as an enum singleton only when you can name why there must be one, and inject Clock, config, and gateways into OrderProcessor instead of AppContext.getInstance().
Read MoreTry JEP 531 in JDK 27: LazyConstant.of, List/Map/Set.ofLazy, and one-time thread-safe init the JIT can constant-fold — without double-checked locking.
Read MoreLevenshtein distance on a DP grid: insert, delete, substitute, and recover one alignment — related to LCS, a different job.
Read MoreReplace a telescoping ChargeRequest constructor with a Java builder so required checkout fields stay required, optional ones stay optional, and the product can still be a record.
Read MoreWrap a vendor client whose methods do not match PaymentGateway so OrderProcessor keeps calling charge(Order, BigDecimal) and never learns PayPal’s shape.
Read MoreImplement equals and hashCode so HashMap and HashSet can find the key you put — Object contract, records, and why a mutable id loses the entry.
Read MoreChoose throw over a sentinel return, close resources with try-with-resources, and wrap checked exceptions at lambda boundaries instead of swallowing them.
Read MoreUse Java generics so List of Order stays a list of orders — type parameters, PECS, erasure, and why raw types still compile.
Read MoreProve an Order pricing rule with plain JUnit 5 — assertions, parameterized tests, and lifecycle — before you reach for a Spring test slice.
Read MoreUse Path and Files to read, copy, and walk directories in the JVM — without new File soup and without turning this into a Linux CLI tutorial.
Read MoreCache order reads with Spring @Cacheable and in-process Caffeine, evict on update, and keep JPA entities out of the cache.
Read MoreVersion the orders schema with Flyway SQL migrations, turn off Hibernate ddl-auto outside local experiments, and prove the script with Testcontainers.
Read MoreTurn Bean Validation failures and domain exceptions into RFC 7807 ProblemDetail responses with @ControllerAdvice so API clients get a body they can actually use.
Read MoreSplit Spring Boot config by profile, bind settings to a @ConfigurationProperties record, and inject secrets from the environment instead of committing them in the jar.
Read MoreReplace ad-hoc HTTP calls with Spring Boot 3 RestClient: inject the managed Builder, set timeouts, map JSON to records, and handle status codes without RestTemplate ceremony.
Read MoreLongest increasing subsequence: the O(n²) best-ending-here table, then patience / tails plus binary search for n log n.
Read MoreReplace AuditedRetryingCachedGateway subclasses with PaymentGateway wrappers you compose at the edge — logging, retry, cache — without a new type per combination.
Read MoreFind the longest common subsequence of two strings with a DP grid: match or skip, then reconstruct one shared sequence.
Read MoreStop editing OrderProcessor for every new notification channel by publishing a payment event and letting EmailNotifier and AuditLog subscribe.
Read MoreMove construction of DiscountPolicy and PaymentGateway behind a polymorphic creator so six controllers stop naming PercentOff and StripeGateway.
Read MoreWhat the Java 27 PEM API is (JEP 538): encode and decode keys, certificates, and CRLs with PEMEncoder and PEMDecoder — no BouncyCastle, no sun.security.util.
Read MoreMake change when each denomination may be used again: min-coins and count combinations, and why this is not 0/1 knapsack.
Read MoreReplace a growing discount if/else with a Strategy in Java so each new promotion is a class you add, not a branch you edit into OrderProcessor.
Read MoreWhat Leyden AOT caches are (JEP 483, 514, 515, 516): train a HotSpot cache, then start faster and warm up sooner — still a JVM, not a GraalVM native image.
Read MoreFill a capacity with pick-or-skip DP: each item once, a 2D table or a 1D roll, and how to reconstruct which items went in.
Read MoreA map of creational, structural, and behavioral patterns — what pain each one solves, when to skip it, and links to every post in this series.
Read MoreWhat Java 27 JEP 527 is: hybrid ML-KEM + ECDHE named groups in TLS 1.3 so JSSE sessions survive store-now-decrypt-later — without writing crypto.
Read MoreWhat Java 26 HttpClient HTTP/3 support is (JEP 517): opt in with Version.HTTP_3, fallback vs HTTP_3_URI_ONLY, and why the default stays HTTP/2.
Read MoreSort every undirected edge cheapest-first, skip endpoints already in the same Union-Find component, accept the rest until n-1 edges — an MST that is not a shortest path from a source.
Read MoreWhat JEP 500 does in Java 26: warn (not fail) when deep reflection mutates final fields, how to find the callers, and how to stop needing that hole.
Read MoreOrder the heap by f = g + h, settle toward a goal when h never overestimates remaining cost, and skip stale pairs like Dijkstra — the same procedure with a heuristic that may guess low, never high.
Read MoreFill a dense distance matrix by relaxing every triple (k, i, j) — all-pairs shortest paths when n³ is the bill you can pay, and a negative on the diagonal is a negative cycle.
Read MoreWhat the Java 25 KDF API is (JEP 510): derive AES and HMAC keys with javax.crypto.KDF and HKDF-SHA256 instead of HMAC-then-truncate or a copied StackOverflow HKDF.
Read MoreWhat Java 25 module import declarations are (JEP 511): import module M brings exported types into simple-name scope, how java.se and java.base fit, and how to resolve List clashes.
Read MoreRelax every edge V-1 times, then one more pass for a negative cycle — single-source shortest path when a weight is allowed to be negative.
Read MoreWhat flexible constructor bodies are (JEP 513 / Java 25): validate args and initialize fields in a constructor prologue before super() or this(), without the static-helper hack.
Read MoreGrow a min-heap frontier by current distance, settle each vertex once, and lazy-repush instead of decrease-key — the weighted cousin of BFS when every edge weight is non-negative.
Read MoreWhat compact source files are (JEP 512 / Java 25): implicit classes, instance main methods, java.lang.IO, and automatic java.base imports — without public static void main ceremony.
Read MoreDFS to record finish order, transpose the digraph, DFS again in reverse finish order — each second-pass tree is a strongly connected component, and the condensation is a DAG.
Read MoreWhat JEP 519 compact object headers are: shrink 64-bit HotSpot headers from 12–16 bytes to 8 without changing application source, how to enable the flag on 24/25, and why Java 27 turns it on by default.
Read MoreBuild an observable Spring Boot service with Actuator health probes, Prometheus metrics, W3C trace context, request IDs, and production-safe endpoint security.
Read MoreWhat the Java 24 Class-File API is (JEP 484): parse, generate, and transform .class files with java.lang.classfile so tools track the class-file format without a third-party ASM lag.
Read MoreChoose focused Spring Boot test slices and verify a Spring Data JPA repository against a real PostgreSQL database with Testcontainers.
Read MoreWhat Java 23 Markdown documentation comments are (JEP 467): adjacent /// lines, CommonMark plus GFM tables, and how @param and {@link} still work beside /** */.
Read MoreTurn a Spring Boot API into an OAuth2 resource server, validate JWTs locally, and authorize business actions with method security instead of trusting the edge alone.
Read MoreWhat Java 22 FFM is (JEP 454): Arena, MemorySegment, and Linker downcalls so you can call native code and manage off-heap memory without JNI.
Read MoreDesign a Spring Boot 3 REST boundary with Java records, Bean Validation, Jackson, and explicit mapping to service-owned models.
Read MoreLearn where Java 22 lets you use underscore for intentionally unused locals, catch parameters, lambda parameters, type patterns, and nested record patterns.
Read MoreBuild a safe Spring Data JPA boundary with proxy-friendly entities, record DTOs, explicit fetch plans, and service-owned transactions.
Read MoreWhat Java Stream Gatherers are (JEP 485 / Java 24), why map/filter/flatMap hit a wall, built-ins like windowFixed and fold, and how to write a short custom gatherer.
Read MoreGo beyond map/filter/collect: groupingBy, teeing, takeWhile/dropWhile, short-circuit order, primitive streams, parallel pitfalls, and Stream best practices for production Java.
Read MoreA beginner-to-intermediate guide to Java Streams: source → filter/map/flatMap → collect, lazy pipelines, and when a plain for loop is clearer.
Read MoreEnable spring.threads.virtual.enabled on Boot 3.2+, understand what Tomcat and the application task executor actually switch, and size Hikari, RestClient, and observability so the flag does not become a thundering herd.
Read MoreEmit each vertex only after its predecessors — Kahn with indegree and a queue, or DFS reverse finish times — and treat leftover vertices as a cycle.
Read MoreWhat Java scoped values are (JEP 506 / Java 25), how they differ from ThreadLocal, why they fit virtual threads, and how to bind request context with where/run and where/call.
Read MoreLearn the JDK 27 StructuredTaskScope factory API, Joiner policies, fan-in, sibling cancellation, and how structured concurrency fits virtual threads and scoped values.
Read MoreWhat sealed classes are (JEP 409 / Java 17), how pattern switch and record patterns finish the story on Java 21, and how to replace cascading instanceof with compiler-checked exhaustiveness.
Read MoreAfter virtual threads, when intrinsic locks still win — pinning vs JEP 491, wait/notify, monitors, and ReentrantLock — so you do not treat synchronized as obsolete.
Read MoreWhat Java virtual threads are (JEP 444 / Java 21), how they differ from platform threads, when they win for I/O-bound work, and the pinning and ThreadLocal gotchas—plus what Java 25 changed.
Read MoreWhat Java records are, when they shipped (JEP 395 / Java 16), the problem they solve, and practical use cases with code—from DTOs to sealed-pattern matching.
Read MoreWalk one order/payment notification service through all five SOLID principles end to end — the seams that matter, the ones that do not, and when to stop applying the checklist.
Read MoreApply Dependency Inversion in Java: move Stripe and SMTP construction out of OrderProcessor, inject abstractions, and see how Spring DI is one wiring option — not the principle itself.
Read MoreWhen to put an API gateway in front of your services, the trade-offs that matter, and a working Spring Cloud Gateway Server Web MVC example on the Servlet stack.
Read MoreApply Interface Segregation in Java: break a fat PaymentOperations interface into client-shaped seams so charge, refund, and report clients stop stubbing unused methods.
Read MoreDetect a directed cycle with 3-color DFS (gray means on the recursion stack) and an undirected cycle by skipping the parent — a visited flag alone is the diamond trap.
Read MoreSpot Liskov Substitution violations in Java inheritance — UnsupportedOperationException, tightened preconditions, null surprises — and replace dishonest subtypes with honest types.
Read MoreWalk a graph with DFS, stamp finish times, run the same walk on an ArrayDeque, and recognize a back edge as the shape of a cycle.
Read MoreApply the Open-Closed Principle in Java: replace growing if/switch payment forests with extension seams so new providers are added, not edited into the core.
Read MoreWhat the Single Responsibility Principle actually means — one audience, one reason to change — with a Java OrderProcessor god class split into cohesive pieces.
Read MoreWhat SOLID means in practice, a glossary of the five principles, when they become cargo-cult, and a map of this series — with a shared order/payment domain for later posts.
Read MoreUse Collection.stream, parallelStream, spliterator characteristics, and Collectors.toCollection to leave a collection and land in the right one — without re-teaching Stream.map.
Read MoreVisit vertices in hop order with a FIFO queue — level order and unweighted shortest path — and see why a stack is the wrong frontier.
Read MoreUse ConcurrentLinkedQueue and ConcurrentLinkedDeque for non-blocking ends, and ConcurrentSkipListMap/Set when you need a concurrent sorted map — not a BlockingQueue and not a HashMap.
Read MoreSort RAM-sized chunks, write runs to disk, then k-way merge with a heap of heads — the in-memory merge-sort cousin when the file cannot be loaded.
Read MoreUse BlockingQueue to pass work between threads — put/take that block, offer/poll with timeouts, and when to pick Array, Linked, Delay, Synchronous, or Transfer queues.
Read MoreNatural runs, insertion on short runs, then merge — what object Arrays.sort and Collections.sort actually run, and why you should not hand-roll it.
Read MoreUse CopyOnWriteArrayList and CopyOnWriteArraySet when iteration is the hot path — every mutation copies the array, and iterators walk a snapshot.
Read MoreLSD digit passes as counting sort, when integer or string keys have a digit layout, and why Arrays.sort is not this.
Read MoreUse ConcurrentHashMap for a shared map — per-bin concurrency, no nulls, weakly consistent iterators, and atomic compute/merge — not Hashtable and not synchronizedMap.
Read MoreHistogram, prefix of counts, and a stable place-from-the-right pass when keys come from a small universe.
Read MoreRecognize Vector, Stack, Hashtable, Dictionary, Enumeration, and Properties as legacy — synchronized whole-table types you should not choose for new code.
Read MoreBuild a max-heap and extract the max into the tail — guaranteed O(n log n), little extra memory, and why PriorityQueue poll-all is not this procedure.
Read MoreUse Collections and Arrays for sort, binarySearch, shuffle, nCopies, emptyXxx, synchronized wrappers, and asList — the static methods around the types, not a fourth List implementation.
Read MorePartition around a pivot and recurse — and why last-element vs random vs median-of-three vs dual-pivot is the algorithm, not textbook Lomuto as Arrays.sort.
Read MoreUse List.of, Set.of, Map.of, and copyOf for unmodifiable collections that reject nulls — Java 9 factories, not Collections.unmodifiableList wrapping a live ArrayList.
Read MoreSplit, sort the halves, merge two sorted runs — why the extra array buys a guaranteed O(n log n) bound and stability, and what object Arrays.sort actually runs.
Read MoreInsertion still earns a seat on small or nearly-sorted ranges; selection swaps the min into place; bubble is a whiteboard name — none of them are the production default.
Read MoreUse IdentityHashMap when keys are compared with ==, and WeakHashMap when the GC should drop entries whose keys are otherwise unreachable — two unusual maps, two different jobs.
Read MoreUse EnumSet and EnumMap when the key universe is an enum — a bit vector and an ordinal array, not a hash table.
Read MoreSort by start, sweep, and merge overlapping calendar or busy ranges — and when this is not interval scheduling.
Read MoreA decision guide for the data-structures series: given the hot operation, which layout and which JDK type — with links to every post in the series.
Read MoreRunning best ending here, empty-array and all-negative pitfalls, and why this is one pass of DP you do not need to name as a table.
Read MoreSpatial trees split the plane so range and nearest-neighbor queries skip whole regions. Quadtrees cut into four boxes; k-d trees alternate axis splits.
Read MoreInclusive vs exclusive prefixes, a 2D sketch, difference arrays for range updates, and when a Fenwick or segment tree is the next bill.
Read MoreFixed and variable windows, the add-right / drop-left invariant, and why this is not the same thing as a rate-limit window.
Read MoreA suffix array is the sorted list of a string’s suffixes as start indices. Binary search finds substrings; a short section contrasts the heavier suffix tree.
Read MoreA treap is a BST on keys and a heap on random priorities. Rotations restore heap order so the shape stays balanced in expectation without color bits.
Read MoreOpposite-end, pair-sum on sorted data, and fast/slow — when two indexes replace O(n²) and when they are just two indexes.
Read MoreA splay tree is a BST that rotates the accessed node to the root. Recently used keys get cheap; amortized O(log n) without storing balance factors.
Read MoreThe sorted invariant, lower and upper bound, off-by-one, and what Arrays.binarySearch encodes when the key is missing.
Read MoreLeast-recently-used eviction is O(1) only when a hash map points at nodes of a doubly linked list. How the two layouts share the work, and LinkedHashMap as the JDK shortcut.
Read MoreA map of search, sort, graphs, strings, DP, and systems algorithms — what job each one solves, when to skip it, and a living index of every post in this series.
Read MoreA Bloom filter is a bit array plus k hashes. It can say definitely not in the set, or maybe yes. False positives are the trade for tiny memory — never a false negative.
Read MoreUse TreeSet and TreeMap when keys must stay sorted — O(log n) red-black trees, Navigable ceiling/floor, and a Comparator that stays consistent with equals.
Read MoreA skip list is a layered linked list where higher levels skip ahead. Expected O(log n) search without tree rotations — Redis and ConcurrentSkipListMap use this idea.
Read MoreUse PriorityQueue when you need the next-best element in O(log n) — a heap, not a sorted list, and not a FIFO queue.
Read MoreA Fenwick tree (BIT) stores prefix aggregates in an array using least-significant-bit jumps. Point update and prefix query in O(log n) with less machinery than a segment tree.
Read MoreUse LinkedHashMap when a hash map must iterate in insertion order — or access order with removeEldestEntry for a bounded LRU.
Read MoreA segment tree stores aggregates of array ranges in a binary tree of intervals. Point update and range query in O(log n) without walking the whole slice each time.
Read MoreUse LinkedList only when you need List and Deque on the same nodes — and why it usually loses to ArrayList for indexes and ArrayDeque for ends.
Read MoreDisjoint sets with find and union: path compression and union by rank so “are these two in the same component?” stays nearly O(1) without storing an adjacency list.
Read MoreUse ArrayDeque as the default deque — a resizable ring buffer for stack and queue work without Vector, Stack, or LinkedList.
Read MoreA trie stores strings by shared prefixes. Autocomplete and dictionary lookup become a walk down characters — not a scan of every word.
Read MoreUse HashMap as the default Map — hash spreading, buckets, treeify, resize, and why a mutable key makes an entry disappear.
Read MoreA graph is vertices and edges. Adjacency list vs matrix, directed vs undirected, weighted vs not — choose the representation before you think about an algorithm.
Read MoreUse HashSet for uniqueness and LinkedHashSet when uniqueness still needs insertion order — both are HashMap wrappers, and neither is a sorted set.
Read MoreA binary heap is a complete tree in an array that keeps the next-best element at the root. Min vs max, PriorityQueue in the JDK, and why you will hear Fibonacci heap without implementing one.
Read MoreUse ArrayList as the default List — amortized append, O(1) get, ensureCapacity, and the fail-fast iterator — and know when growth copies the whole array.
Read MoreA B-tree packs many keys per node so one disk page is one hop. Why databases and filesystems use this shape, and how B+ trees keep values in the leaves.
Read MoreUse Map as mappings, not a Collection — get/put, compute and merge, and the keySet/values/entrySet views that write through to the same storage.
Read MoreA red-black tree is a BST painted with color rules that keep height logarithmic without AVL’s strict balance. Why TreeMap and TreeSet use this shape.
Read MoreUse Queue and Deque when the job is the ends — offer/poll versus add/remove, exception versus special value, and why indexes are the wrong primitive.
Read MoreAn AVL tree is a BST that rebalances on insert and delete so height stays O(log n). Balance factors, rotations, and when the extra strictness is worth it versus red-black.
Read MoreUse Set when uniqueness is the job — equals-based membership, no indexes, and why List.contains is the wrong uniqueness type.
Read MoreA BST keeps left < node < right so search is O(height). Why already-sorted inserts become a linked list, and what that does to the bill.
Read MoreUse List as an indexed contract — get/set, subList views, sort/replaceAll, and RandomAccess — without treating every List like an ArrayList.
Read MoreA binary tree is a hierarchical layout: left, right, parent. Height vs size, preorder inorder postorder and level-order as operations of the shape, and what balanced actually promises.
Read MoreThe set ADT is unique membership. HashSet delivers it with a hash table; List.contains is a scan. When TreeSet belongs instead, and what you lose (order).
Read MoreUse Collection and Iterator as the shared contract — optional operations, fail-fast iteration, bulk methods, and removeIf — before you pick ArrayList or HashSet.
Read MoreThe Java Collections Framework as a map: hierarchy, glossary, a nulls-order-threads matrix, and a living catalog of every post in this series.
Read MoreHow hashing maps a key to a bucket, what chaining and open addressing do with collisions, and why HashMap is expected O(1) — not a law of physics.
Read MoreA double-ended queue lets you push and pop at both ends in O(1). How ArrayDeque delivers that in the JDK, and when a deque is a stack, a queue, or a sliding window.
Read MoreFIFO as an ADT: enqueue, dequeue, and why a naive array queue slides or wastes space — and how a circular buffer (ring) fixes both.
Read MoreLIFO as an ADT: push, pop, peek, and why undo, brace matching, and the call stack are the same layout — implemented with ArrayDeque, not java.util.Stack.
Read MoreHow node-and-pointer lists make splice cheap when you already hold the node, why get(i) walks, and how singly, doubly, and circular variants differ.
Read MoreHow ArrayList grows by doubling, why append is amortized O(1) not a guarantee on the next call, and when a fixed array is the honest choice.
Read MoreHow a contiguous array makes index i O(1), why insert and delete in the middle slide everything, and how a 2D matrix is still the same layout.
Read MoreA beginner-to-advanced path through data structures: glossary, Big-O literacy, a JDK map, and a living index of every post in this series.
Read MoreJava 15 text blocks (JEP 378): triple-quote multiline strings, incidental indentation, and escape sequences — JSON, SQL, and HTML without + concatenation.
Read MoreJava 14 switch expressions (JEP 361): arrow cases, yield, exhaustiveness — return a value without fall-through breaks. Pattern switch lives in a later post.
Read MoreUse Java 11 java.net.http.HttpClient for HTTP/1.1 and HTTP/2 — builder, sync and async send, body handlers — without Apache HttpClient or OkHttp for ordinary calls.
Read MoreJava 10 var (JEP 286): use local-variable type inference when the right-hand side already names the type, and skip it when var hides what the reader needs.
Read MoreWhat JPMS (JEP 261) actually buys: explicit exports, requires, and a smaller runtime — not a file you copy into every repo. import module is a later language convenience.
Read MoreCompose async Java work with CompletableFuture — supplyAsync, thenApply, thenCompose, allOf — without nested callbacks, and when virtual threads are the simpler path.
Read MoreReplace Calendar and SimpleDateFormat with java.time — Instant, LocalDate, ZonedDateTime, formatting, and a Clock you can fake in tests.
Read MoreUse java.util.Optional to return absence without null — of/ofNullable, map/flatMap/filter, orElse vs orElseGet, and when wrapping every call is cargo-cult.
Read MoreUse java.util.function’s primitive SAM grid to skip boxing on hot numeric paths, fill IntStream slots, and leave ToIntFunction out of ordinary application code.
Read MoreUse BiFunction, BiPredicate, and BiConsumer for two-argument slots — apply, test, accept — and fill Map.merge, compute, and forEach without inventing a pair type.
Read MoreUse UnaryOperator and BinaryOperator when input and output are the same type — List.replaceAll, Stream.reduce, Collectors.reducing, and minBy / maxBy.
Read MoreUse Java’s Supplier<T> for lazy values — get, orElseGet, factories, supplyAsync — so you do not build work until something actually needs the result.
Read MoreUse Java’s Consumer<T> for side effects — accept, andThen — and see where Stream.forEach, Optional.ifPresent, and peek already ask for it.
Read MoreUse Java’s Predicate<T> to test values — test, and, or, negate, isEqual, Predicate.not (Java 11) — and see where Stream.filter, anyMatch, and removeIf already ask for it.
Read MoreUse Java’s Function<T,R> to map values — apply, compose, andThen, identity — and see where Stream.map, Optional.map, and Collectors already ask for it.
Read MoreWhat a Java functional interface is, the four shapes in java.util.function, when to write your own SAM type, and a living map of every post in this series.
Read More