2dbi

Implement sorting with Java Streams

viaGlassdoor

Problem Sort a collection of objects using the Java Streams API, then extend it to multi-key ordering. Be able to fall back to implementing a sort manually if asked.

Input / Output

  • Input: a List<T> (e.g. employees) and one or more sort keys.
  • Output: a new sorted list (Streams are non-mutating).

Expected approach

  • list.stream().sorted(Comparator.comparing(T::key)).collect(toList()).
  • Multi-key: Comparator.comparing(...).thenComparing(...), reversed(), and nullsFirst/nullsLast for null handling.
  • Discuss stability of the sort, parallelStream() and when it helps/hurts, and the underlying O(n log n) cost.

Discussion points

  • Difference between sorted() and sorting the source list in place (Collections.sort).
  • Comparator vs Comparable (natural ordering).
  • Pitfalls of mutating shared state inside a stream pipeline.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account