From an API-design standpoint, why is Iterable separate from Collection, and why did the designers keep Map outside the Collection hierarchy? What does this teach about interface segregation?
answer
- Iterable = minimal 'traversable' capability (ISP)
- non-collections (lazy/infinite/cursors) can be Iterable
- pairs alone: no lookup or delete by key
- mappings are not collections -> expose views
- accept Iterable, return Collection - weakest sufficient type
basics
~20 sIterable carries only traversal, so non-collections such as Path, ServiceLoader and DirectoryStream work in for-each without a Collection's other methods. Map stays separate by design: as a mere collection of pairs it could not look up or delete by key.
solid answer
~50 sThe split reads as interface segregation: a caller that only traverses should depend on nothing more. Iterable, added in Java 5 above the existing Collection, promises just 'you can ask me for an Iterator', which makes an object a target of for-each. That is far weaker than Collection (size, add/remove, contains, bulk ops), so non-collections such as Path, ServiceLoader and DirectoryStream qualify without pretending to be collections. Map stays out by design: the JDK's design FAQ says that if a Map were a Collection, its only reasonable elements would be key-value pairs, and that abstraction is too limited, because you couldn't ask what value a key maps to or delete by key alone. So Map exposes collection-shaped views instead (keySet/values/entrySet). The lesson: model the narrowest truthful contract, and prefer composition (views) over a subtype relationship that would weaken the abstraction.
go deeper
Can state that Iterable just means 'usable in for-each' and that Map is separate by design, because a mere collection of pairs could not look up by key.
Explains why pairs alone make a limited Map (no lookup or delete by key) and that Map exposes views instead of being a Collection.
Frames the split via ISP, gives the design FAQ's reason for Map (pairs alone make a limited abstraction), and knows to accept Iterable when only iterating.
Reasons about the design trade-offs end to end (counterfactuals, default methods as the evolution path, composition over inheritance, weakest-sufficient-type API contracts) and could defend or critique the JDK's choice.
## The question behind the question This is really about **interface design**: how the JDK authors decided *what promises each interface makes* and *who is allowed to implement it*. Two choices stand out: (a) `Iterable` is a separate, tinier interface *above* `Collection`, and (b) `Map` is deliberately **not** a `Collection`. ## Background terms - **Interface Segregation Principle (ISP):** the 'I' in SOLID - clients should not be forced to depend on methods they don't use; prefer many small, focused interfaces over one fat one. - **Liskov Substitution Principle (LSP):** a subtype must be usable anywhere its supertype is, *honoring the supertype's contract*. A subtype that can't honestly fulfill the contract shouldn't be a subtype. - **Reified vs erased / capability:** here, the relevant idea is matching an interface to the *capability* a type can truthfully provide. These are an interviewer's lens: the JDK's own Design FAQ argues from what a map *is* and names neither principle. ## Why Iterable is separate from Collection `Collection<E>` is a **rich** contract: `size()`, `isEmpty()`, `add`, `remove`, `contains`, the bulk ops, `toArray`, plus `iterator()`. Many things in software can be **traversed** but are **not** full collections: - A **lazy or infinite sequence** (e.g. all natural numbers) - it has no `size()`, you can't `add` to it, but you *can* walk it. - A **resource-backed cursor** - lines of a file, rows of a result set; traversable once, not a stored container. `java.nio.file.DirectoryStream` is the JDK's own: its Javadoc says it "supports only a single" iterator, and a second `iterator()` call throws `IllegalStateException`. - A **stream source** - an implementer writes only `iterator()`, and the default `spliterator()` can feed `StreamSupport.stream(...)`. (`Stream` itself is not `Iterable`.) If for-each had required `Collection`, none of these could use the clean loop syntax, and you'd be forced to implement (or throw `UnsupportedOperationException` from) a dozen irrelevant methods. `Iterable` arrived in Java 5 with for-each, above a `Collection` that dates from 1.2. By extracting the **minimal** capability - *"I can produce a cursor"* - into it, the JDK lets all of the above participate in for-each and streams while only promising what they can deliver. This is **ISP in action**: depend on `Iterable<T>` in an API when all you need is to traverse; depend on `Collection`/`List` only when you need their extra powers. When Java 8 added streams, `Iterable.spliterator()` and `Collection.stream()` came as **default methods**, so existing implementers kept linking. That is the default-method mechanism at work, not the split, and JLS §13.5.7 notes a default method can still introduce errors "at compile time or invocation time". ## Why Map is NOT a Collection `Collection<E>` is defined *entirely* in terms of **one** element type `E`: `add(E)`, `remove(Object)`, `contains(Object)`, `iterator()` yielding `E`, `toArray()` of elements. A **`Map<K,V>`** stores **pairs** and has **two** type parameters. The JDK's Collections API Design FAQ answers this directly: "This was by design. We feel that mappings are not collections and collections are not mappings." Its argument starts from the element type: "If a Map is a Collection, what are the elements? The only reasonable answer is 'Key-value pairs', but this provides a very limited (and not particularly useful) Map abstraction." So pairs can be expressed, and `entrySet()` really is a `Set<Map.Entry<K,V>>`. What pairs alone can't express is a map: - **Lookup by key** - `contains(Object)` takes a whole entry: "You can't ask what value a given key maps to". - **Delete by key** - `remove(Object)` takes a whole entry too: "nor can you delete the entry for a given key without knowing what value it maps to". - **`add(entry)` on an existing key** - replace or refuse? `Collection` leaves that to each implementer, and a map needs one answer. The reverse fails as well: "Collection could be made to extend Map, but this raises the question: what are the keys? There's no really satisfactory answer, and forcing one leads to an unnatural interface." Interviewers often restate this through **LSP**: a `Map` handed to code expecting a `Collection` would surprise it on `add`. That is a fair lens, not the FAQ's own wording. The designers chose **composition over (inappropriate) inheritance**: `Map` is its own interface, and it *exposes* collection-shaped **views** - `keySet()` (a `Set<K>`), `values()` (a `Collection<V>`), `entrySet()` (a `Set<Map.Entry<K,V>>`). Those views are live (backed by the map), giving you all the Collection power *where it actually makes sense* without pretending the Map itself is a Collection. ## What this teaches 1. **Model the narrowest truthful contract.** `Iterable` promises only traversal; that single, honest promise makes it reusable far beyond collections. 2. **Don't force a subtype relationship that weakens the abstraction.** When a type isn't really a kind of its would-be supertype, expose the overlap via **views/adapters** (composition) instead. 3. **Small interfaces compose well** (ISP). A type can be `Iterable` without taking on any of `Collection`'s duties. 4. **APIs should accept the weakest type that suffices** - take `Iterable<T>` when you only iterate, return `List`/`Collection` when callers need more. ## Counterfactual Had the designers made `Map extends Collection<Map.Entry<K,V>>`, you'd gain a uniform `iterator()` but lose key-based clarity and invite awkward contract questions (what does `add(entry)` mean if the key exists?). Today's two interfaces can't even be combined: `javac` rejects `interface M<K,V> extends Map<K,V>, Collection<Map.Entry<K,V>>` because "both define remove(Object), but with unrelated return types". The chosen design - separate interface + views - is the cleaner trade.
- If you were designing a method that only loops over its input, what parameter type should you accept and why?Iterable<T> (or Stream/Collection only if you need more). Accepting the weakest sufficient type maximizes the callers that can use your method - lazy sequences, custom cursors, any collection - which is exactly the ISP benefit Iterable provides.
- What would you lose by making Map extend Collection<Map.Entry<K,V>>?The JDK's design FAQ says a Map defined by its pairs couldn't answer what value a key maps to, or delete an entry without knowing its value. add(entry) on an existing key would need a rule too, and Map.remove(Object) and Collection.remove(Object) clash on return type. Views give the collection shape without any of this.
- Saying Map is just an oversight rather than a deliberate contract decision
- Claiming Iterable and Collection are redundant
- Arguing Map should extend Collection<Map.Entry> without seeing that lookup and delete by key would suffer
- Treating ISP/LSP as buzzwords without tying them to the concrete cost: no lookup or delete by key
- Claiming a Map cannot have a single element type at all (entrySet is exactly a Set of pairs)
- Iterable
- Java 1.5
- Collection and Map
- Java 1.2
context
- Java Collections API Design FAQdocs.oracle.com
- Iterable (Java SE 27 & JDK 27)docs.oracle.com
- DirectoryStream (Java SE 27 & JDK 27)docs.oracle.com