Java Stream API Program · OT60
Group and Count Items Using Streams in Java
Pick a key for each item, such as its first letter. groupingBy() collects items with the same key, and counting() turns each group into a number.
Problem Statement
Given a list of strings, count how many share each first letter, and separately how many share each length. Return the counts sorted by key.
An empty list gives an empty map.
Input/Output Examples
[mango, melon, kiwi, lime, lemon, mint]Output{k=1, l=2, m=3}Explanation: mango, melon and mint start with m.same listOutput{4=3, 5=3}Explanation: kiwi, lime and mint have 4 letters.[]Output{}Explanation: no groups.Visual Explanation
counting() reports each group's size.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().
Approach 1: groupingBy() With counting() (Recommended)
Idea: collect with groupingBy(keyFunction, TreeMap::new, Collectors.counting()).
- Choose the key function, such as
s -> s.charAt(0). - Pass
TreeMap::newfor sorted keys. - Use
counting()as the downstream collector.
Time: O(n log k) · Space: O(k). k is the number of distinct keys.
Approach 2: Loop With merge()
Idea: compute the key for each item and call counts.merge(key, 1L, Long::sum).
- Create a
TreeMap. - For each item, merge 1 into its key's count.
- Return the map.
Time: O(n log k) · Space: O(k).
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.
Approach 1: groupingBy() With counting() (Recommended)
Swap counting() for summingInt(), averagingDouble() or toList() to get other summaries.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class GroupCountStream {
// groupingBy(key, TreeMap::new, counting()) counts the items for each key, sorted by key
static Map<Character, Long> byFirstLetter(List<String> items) {
return items.stream()
.collect(Collectors.groupingBy(s -> s.charAt(0), TreeMap::new, Collectors.counting()));
}
static Map<Integer, Long> byLength(List<String> items) {
return items.stream()
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
}
public static void main(String[] args) {
List<String> fruits = List.of("mango", "melon", "kiwi", "lime", "lemon", "mint");
System.out.println("by first letter: " + byFirstLetter(fruits));
System.out.println("by length: " + byLength(fruits));
System.out.println("empty list: " + byFirstLetter(List.of()));
}
}
by first letter: {k=1, l=2, m=3}
by length: {4=3, 5=3}
empty list: {}
Time complexity: O(n log k) · Space complexity: O(k).
Approach 2: Loop With merge()
The same result without streams, useful for comparison.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class GroupCountLoop {
// The same counts with a loop and Map.merge()
static Map<Character, Long> byFirstLetter(List<String> items) {
Map<Character, Long> counts = new TreeMap<>();
for (String s : items) {
counts.merge(s.charAt(0), 1L, Long::sum);
}
return counts;
}
static Map<Integer, Long> byLength(List<String> items) {
Map<Integer, Long> counts = new TreeMap<>();
for (String s : items) {
counts.merge(s.length(), 1L, Long::sum);
}
return counts;
}
public static void main(String[] args) {
List<String> fruits = List.of("mango", "melon", "kiwi", "lime", "lemon", "mint");
System.out.println("by first letter: " + byFirstLetter(fruits));
System.out.println("by length: " + byLength(fruits));
System.out.println("empty list: " + byFirstLetter(List.of()));
}
}
by first letter: {k=1, l=2, m=3}
by length: {4=3, 5=3}
empty list: {}
Time complexity: O(n log k) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| groupingBy() With counting() | O(n log k) | O(k) |
| Loop With merge() | O(n log k) | O(k) |
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::newfor sorted keys,LinkedHashMap::newfor first-seen order. - Know
counting()returnsLong. UsesummingInt(x -> 1)forIntegercounts. - 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.