skip to content

What are Spliterator characteristics, and how does the Streams API use flags like ORDERED, SIZED, DISTINCT, SORTED, and IMMUTABLE?

level: seniorimportance: should knowfreq 45%

answer

  1. characteristics() = bitmask; the pipeline trusts several
  2. DISTINCT skips distinct(); natural SORTED skips sorted()
  3. SIZED: preallocation, count; SUBSIZED: one shared array
  4. ORDERED → findFirst/limit/forEachOrdered must preserve order; unordered() drops it
  5. IMMUTABLE vs CONCURRENT vs fail-fast; flags must be truthful

basics

~20 s

Characteristics are flags a Spliterator reports about its data: the elements are ordered, the exact count is known, all are unique, or the source can't change. The stream pipeline reads several of them to skip unnecessary work.

solid answer

~50 s

characteristics() returns a bitmask describing the source. Key flags: ORDERED (a meaningful encounter order exists — lists, arrays; absent for HashSet), SIZED (estimateSize is exact), SUBSIZED (children of a split are also exactly sized), DISTINCT (no duplicates — Sets), SORTED (elements follow a sort order, implies ORDERED), NONNULL (no null elements), IMMUTABLE (elements can't be added, replaced or removed) and CONCURRENT (source can be safely modified concurrently). The pipeline exploits a few: distinct() on a DISTINCT source skips the work; sorted() is skipped only for natural order, never for a custom comparator (JDK 27 also recognises Comparator.naturalOrder(), JDK 25 does not); SIZED lets toArray preallocate and count() answer without traversing; SUBSIZED lets a parallel toArray fill one shared array; ORDERED obliges findFirst, limit and forEachOrdered to preserve order, which unordered() can relax. IMMUTABLE, CONCURRENT and NONNULL drive no pipeline optimization. Flags must be truthful: a false one causes wrong results.

go deeper

for a junior

Can name a few flags (ordered, sized, distinct) and say they describe the data so streams can optimize.

for a middle

Explains specific optimizations: DISTINCT skips distinct(), SIZED preallocates, and that HashSet is not ORDERED.

for a senior

Covers the full flag set including SUBSIZED, SORTED-implies-ORDERED, CONCURRENT vs IMMUTABLE, and the ordering/coordination cost that unordered() removes; stresses flags must be truthful.

for a principal

Reasons about correctness risk of mis-reported flags, designs custom Spliterators with the right minimal honest flag set, and weighs unordered()/order-preservation trade-offs in real parallel pipelines.

## What "characteristics" are `int characteristics()` returns a **bitmask** — an integer whose individual bits each stand for a property of the Spliterator's source. You test a flag with `spliterator.hasCharacteristics(Spliterator.SIZED)`. These flags are a **contract the Spliterator makes to its clients**: the stream pipeline trusts several of them to skip work, so they must be **truthful**. ## The flags, defined - **`ORDERED`** — the elements have a **meaningful encounter order** (a defined first, second, third…). Lists, arrays, and `LinkedHashSet` are ORDERED; a `HashSet`'s Spliterator is **not** (its iteration order is arbitrary). Order matters for operations like `findFirst`, `limit`, `skip`, and `forEachOrdered`. - **`SIZED`** — before any traversal or split, `estimateSize()` is an **exact** count of the elements, not a guess. Collections of known size report this. - **`SUBSIZED`** — additionally, **every** Spliterator produced by `trySplit` is also exactly `SIZED`. (SUBSIZED implies SIZED for the children.) This lets the parallel framework know precise sizes all the way down the split tree. A `HashSet` reports `SIZED` but not `SUBSIZED`, and its Spliterators lose `SIZED` after a split. - **`DISTINCT`** — no two elements are equal (per `equals`); i.e. there are no duplicates. `Set` sources report this. - **`SORTED`** — the elements are encountered in a defined **sort order**. SORTED **implies ORDERED**. A source reporting SORTED may expose its `Comparator` via `getComparator()` (returning `null` means natural ordering). `TreeSet` reports this. - **`NONNULL`** — the source is guaranteed to contain **no null** elements (e.g. `ConcurrentHashMap` keys). - **`IMMUTABLE`** — the **source cannot be structurally modified**: no elements added, replaced or removed, so it needs no concurrent-modification detection. - **`CONCURRENT`** — the source **may be safely modified concurrently** by other threads during traversal (e.g. `ConcurrentHashMap`). Note: a source is either IMMUTABLE, CONCURRENT, or neither (the "neither" case is the typical fail-fast collection that throws `ConcurrentModificationException`). ## How the Streams API uses them The pipeline carries `ORDERED`, `DISTINCT`, `SORTED` and `SIZED` as internal stream flags and consults `SUBSIZED` directly, to avoid redundant work: - **`DISTINCT` → `distinct()` does no work.** If the source already guarantees uniqueness, the deduplication step is skipped entirely. - **`SORTED` → `sorted()` may be skipped, for natural order only.** `sorted(comparator)` with a custom comparator is not skipped, even over a `TreeSet` built with that same comparator, because the flag is dropped for any non-natural order. The version matters at the edge: on JDK 27, `Comparator.naturalOrder()` counts as natural order, both as the source's comparator and as the argument to `sorted`; on JDK 25 only a source with a null comparator and the no-argument `sorted()` qualify. A naturally ordered `TreeSet` followed by `sorted()` is elided on both. - **`SIZED` → exact preallocation.** `toArray()`, and `Stream.toList()` built on it, can allocate the right size up front instead of growing dynamically. `collect(Collectors.toList())` cannot: it starts from a plain `new ArrayList`. `count()` may return the size directly without traversing, so a `peek` before it may never run. `filter` and `distinct` clear `SIZED`; `map` and `sorted` keep it, and a sequential `skip` or `limit` adjusts it. - **`SUBSIZED` → one shared output array.** A parallel `toArray` can allocate the array up front and let every leaf write at its exact offset, instead of building a tree of partial results. - **`ORDERED` → ordering obligations.** Operations such as `limit`, `skip`, `findFirst` and `forEachOrdered` must honor encounter order. In a **parallel** pipeline, preserving order costs coordination; if you don't need it, calling `unordered()` (or starting from an unordered source like a HashSet) **drops** the ORDERED flag and can make the parallel pipeline faster. - **`IMMUTABLE`, `CONCURRENT`, `NONNULL` → no pipeline optimization.** The internal flags do not carry them. They describe the source's contract instead: a Spliterator reporting neither `IMMUTABLE` nor `CONCURRENT` is expected to document when it binds and how it detects interference, and `StreamSupport` strongly recommends `IMMUTABLE`, `CONCURRENT` or late binding. ## Why truthfulness is mandatory Because the framework *acts* on these flags, **lying corrupts results**. If you report `DISTINCT` but actually have duplicates, `distinct()` is skipped and duplicates leak through. If you report `SIZED` with the wrong count, buffers misallocate. A custom Spliterator must report **only** flags it genuinely satisfies. ## Where the flags come from in practice You rarely set these by hand. Standard collections report sensible defaults: | Source | Typical characteristics | |---|---| | `ArrayList` | ORDERED, SIZED, SUBSIZED | | `HashSet` | DISTINCT, SIZED (not ORDERED) | | `LinkedHashSet` | DISTINCT, ORDERED, SIZED, SUBSIZED | | `TreeSet` | DISTINCT, SORTED, ORDERED, SIZED | | `ConcurrentHashMap` keys | DISTINCT, CONCURRENT, NONNULL | When you build a custom Spliterator (often via `Spliterators.spliterator(...)` helpers), you pass the bitmask, e.g. `ORDERED | SIZED | SUBSIZED | NONNULL`. ## Quick example of reading flags ```java Spliterator<String> s = new TreeSet<>(List.of("a", "b")).spliterator(); s.hasCharacteristics(Spliterator.SORTED); // true s.hasCharacteristics(Spliterator.DISTINCT); // true s.hasCharacteristics(Spliterator.SIZED); // true // SORTED implies ORDERED: s.hasCharacteristics(Spliterator.ORDERED); // true ```

  • Why might calling unordered() speed up a parallel stream?
    Operations like limit, skip, findFirst and forEachOrdered must reconcile results in encounter order, which forces coordination across worker threads; plain forEach never promises that order. unordered() drops the ORDERED flag, letting the framework merge partial results in any order, which can improve parallel throughput when order doesn't matter.
  • What is the difference between IMMUTABLE and CONCURRENT?
    IMMUTABLE means the source cannot be structurally modified: elements cannot be added, replaced or removed, so such changes cannot occur during traversal. CONCURRENT means the source CAN be safely mutated by other threads during traversal (like ConcurrentHashMap). A source reporting neither is typically fail-fast and may throw ConcurrentModificationException if mutated mid-traversal.

  • Claiming HashSet's Spliterator is ORDERED — it is not; LinkedHashSet, TreeSet and lists are
  • Saying SORTED does not imply ORDERED — it does
  • Reporting characteristics you don't honor (e.g. DISTINCT with duplicates) — that silently corrupts results
  • Confusing SIZED with SUBSIZED — SIZED is about this spliterator's count; SUBSIZED is about its split children
  • Thinking unordered() reorders elements — it only drops the ordering obligation so parallel ops can run looser
  • Claiming sorted(comparator) is skipped when the source is already sorted by that comparator — only natural order is elided

Spliterator characteristics
Java 1.8

Assumes JDK 27. sorted() is elided for natural order only, and the edge differs by version: JDK 27 treats Comparator.naturalOrder() as natural order, on the source and as the argument; JDK 25 LTS elides only the no-argument sorted() over a source with a null comparator.

context