Interview Practice

Chapter 2 of 5

Collections, generics and stream pipelines

Choose APIs that make data flow and mutation explicit.
Read aloud is unavailable in this browser. Reading preferences still work.

Pick operations before implementation

List preserves positional sequence, Set represents uniqueness and Map associates keys with values. ArrayList offers direct indexed reads; ArrayDeque offers efficient ends; TreeMap supports comparator-ordered queries. Iteration order, null policies and concurrency vary across implementations. Unmodifiable views can still reflect changes to an underlying collection; copies isolate structure but may still share mutable elements.

Generics constrain safe use

Generic types are invariant: List<Integer> is not a List<Number>. A ? extends Number source can produce values safely read as Number, but its unknown element subtype prevents arbitrary inserts. A ? super Integer destination can consume Integer values, while reading gives only Object without further knowledge. This producer/consumer reasoning is more reliable than memorizing the wildcard syntax alone. Type erasure limits runtime generic type information.

Pipelines are lazy until terminal work

A stream pipeline describes operations and is evaluated by a terminal operation. Avoid side effects on shared mutable state, especially under parallel execution. Reductions require compatible identity/combination behavior and associativity. sorted retains and orders data; collect materializes output; short-circuit operations may avoid full traversal. Parallel streams add coordination overhead and should not be a default response to a slow dependency call.

Worked Java example

Illustrative snippet: imports, surrounding types or collaborators may be omitted. Read the assumptions before adapting it.

int sum = values.stream()
    .filter(value -> value > 0)
    .mapToInt(Integer::intValue)
    .sum();

Walkthrough

filter keeps positive values, mapToInt avoids retaining boxed Integer values for the reduction, and sum is the terminal operation. For [-2, 3, 4] the result is seven. The pipeline does not mutate values. An int sum can overflow, so use a suitable wider type or checked arithmetic when input constraints require it.

Practice it yourself

Explain how adding sorted before sum affects cost, and whether it improves correctness for this operation.

Check your reasoning

Sorting is unnecessary for summing positive values. It introduces O(n log n) sorting time and generally O(n) buffering without changing the mathematical result when no overflow occurs. The original pipeline is O(n) with constant incremental state.

Recall checklist

  • Explain the main invariant or contract without looking.
  • Trace the example and test an edge case.
  • State time, space, input variables and assumptions where relevant.
  • Explain one alternative and when you would choose it.

Read further