00:00

Problem Statement

Input/Output Examples

Visual Explanation

Changing the key function, for example to String::length, changes the grouping without changing anything else in the pipeline.

Approaches

Both approaches produce the same sorted counts. One uses a collector; the other a loop with merge().

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of items and k the number of distinct keys. Each item costs one sorted-map update.

Interview Tips and Recommended Approach

  • Know the three-argument form. Key function, map factory and downstream collector.
  • Pick the map factory. TreeMap::new for sorted keys, LinkedHashMap::new for first-seen order.
  • Know counting() returns Long. Use summingInt(x -> 1) for Integer counts.
  • Group by multiple keys by nesting another groupingBy() as the downstream collector.

Recommended Approach: groupingBy() With counting()

Why: it expresses "count by key" in one call, and the same pattern adapts to any key or summary.