Quick revision
The short answer
For the length map, words.stream().collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting())) gives a Map<Integer, Long> whose keys are sorted because we asked for a TreeMap. For the letter map, we group by w.charAt(0) into a TreeMap and make each group sorted, either by sorting the stream first and collecting each group with toList(), or with collectingAndThen(toList(), l -> { l.sort(null); return l; }). We must handle empty strings before charAt(0), decide on case with toLowerCase(Locale.ROOT), and remember that counting() returns Long, so we use summingInt(w -> 1) if Integer counts are required.
What to remember
In this answer, we used the three-argument groupingBy to choose both the map type and what happens inside each group. groupingBy(String::length, TreeMap::new, counting()) gives a sorted Map<Integer, Long>, with summingInt(w -> 1) for Integer counts. Grouping by the first character into a TreeMap after sorting the stream, or sorting each group with collectingAndThen, gives alphabetical lists. We also filtered empty strings before charAt(0), lowercased with Locale.ROOT, and saw that the default groupingBy map is an unordered HashMap.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For the length map, words.stream().collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting())) gives a Map<Integer, Long> whose keys are sorted because we asked for a TreeMap. For the letter map, we group by w.charAt(0) into a TreeMap and make each group sorted, either by sorting the stream first and collecting each group with toList(), or with collectingAndThen(toList(), l -> { l.sort(null); return l; }). We must handle empty strings before charAt(0), decide on case with toLowerCase(Locale.ROOT), and remember that counting() returns Long, so we use summingInt(w -> 1) if Integer counts are required.
Background to this question
Grouping is the stream operation we use most after map and filter: orders by status, log lines by level, users by country. This question checks that we know the three-argument form of groupingBy, which lets us choose the map type and what happens inside each group, and that we notice the small traps in real data such as empty strings, mixed case and the boxed Long result. In this answer, we will recap how groupingBy works, build the length map, build the first-letter map in two ways, handle the edge cases, and look at the default map type and the Long counts.
1A Quick Recap of groupingBy
Collectors.groupingBy comes in three forms. groupingBy(classifier) puts each element into a list under the key the classifier returns. groupingBy(classifier, downstream) does the same but collects each group with another collector, the downstream, such as counting(). groupingBy(classifier, mapFactory, downstream) also lets us choose the map implementation, for example TreeMap::new for keys in sorted order.
We will use words = List.of("pear", "apple", "fig", "kiwi", "banana", "avocado") throughout. Their lengths are 4, 5, 3, 4, 6 and 7.
2Counting Words by Length, Sorted
We classify by length, ask for a TreeMap so the keys are in ascending order, and count each group.
Notice that the declared type is Map<Integer, Long>. counting() always produces a Long, because a stream can in principle have more than Integer.MAX_VALUE elements. If an API needs Map<Integer, Integer>, summingInt(w -> 1) produces Integer counts directly, which is cleaner than converting afterwards.
Without the TreeMap::new argument the result would usually still print in order here, because small Integer keys happen to land in ascending HashMap buckets. That is an accident of the hash codes, not a promise, and it breaks with larger or negative keys. If the question says sorted, we ask for a sorted map.
3Grouping Words by First Letter, in Alphabetical Order
Now the key is the first character, and each group must be a list in alphabetical order. The simplest way is to sort the stream before grouping. groupingBy keeps the encounter order of elements inside each list, so sorted input produces sorted groups.
- filter out empty strings"" has no first letter
- lowercase with Locale.ROOT"Apple" and "apple" group together
- sorted()natural String order
- groupingBy(charAt(0), TreeMap::new, toList())keys sorted, lists keep encounter order
4 steps in order. Play them, or step through them one at a time.
Sorting before grouping is enough, because each group's list keeps the order elements arrive in.
Sorting the whole stream costs O(n log n) once. Sorting inside each group costs the same in total, but it is independent of how the stream is ordered and still works if someone later removes the sorted() call. l.sort(null) sorts by natural order; Collectors.toList() currently returns a mutable ArrayList, which is why the in-place sort works, though the specification does not promise mutability. Collectors.toCollection(ArrayList::new) makes that guarantee explicit.
The key type is Character, a boxed char, because map keys must be objects. w.charAt(0) returns a char and the lambda's result is boxed automatically.
4Edge Cases in Real Data
Three details turn a demo into production code. Empty strings make charAt(0) throw StringIndexOutOfBoundsException, so we filter them out or give them their own key. Case decides whether Apple and apple share a group; toLowerCase(Locale.ROOT) gives the same result on every server, while the no-argument toLowerCase() depends on the default locale, and in a Turkish locale it turns I into a dotless i.
Sorting order is the third. String's natural order compares UTF-16 code units, so every uppercase letter sorts before every lowercase one and accented letters sort after z. That is fine for codes and identifiers. For words shown to people, a java.text.Collator for the user's locale gives the order a reader expects, and we pass it as the comparator: sorted(Collator.getInstance(Locale.FRENCH)). And if words may start with an emoji, charAt(0) returns half a surrogate pair, so w.codePointAt(0) is the safer key.
5Follow-up questions
What does groupingBy use as the default map type?
The specification gives no guarantee about the type, mutability or thread safety of the map, and in current JDKs the one- and two-argument forms create a HashMap, with an ArrayList for each group when the downstream is toList(). Because HashMap has no meaningful order, any time we need sorted or insertion-ordered keys we pass TreeMap::new or LinkedHashMap::new as the map factory instead of relying on the default.
How would you get the words grouped by length, not just counted?
Use toList() or toSet() as the downstream instead of counting(): groupingBy(String::length, TreeMap::new, Collectors.toList()) gives {3=[fig], 4=[pear, kiwi], 5=[apple], 6=[banana], 7=[avocado]}. If I want only a joined string per group, Collectors.joining(", ") as the downstream does it.
Is groupingBy safe on a parallel stream?
Yes. It is a non-concurrent collector, so each thread builds its own partial maps and the stream merges them, keeping encounter order within each group. For very large parallel inputs where order does not matter, groupingByConcurrent puts everything into one ConcurrentHashMap, which avoids the merge step.
6Conclusion
In this answer, we used the three-argument groupingBy to choose both the map type and what happens inside each group. groupingBy(String::length, TreeMap::new, counting()) gives a sorted Map<Integer, Long>, with summingInt(w -> 1) for Integer counts. Grouping by the first character into a TreeMap after sorting the stream, or sorting each group with collectingAndThen, gives alphabetical lists. We also filtered empty strings before charAt(0), lowercased with Locale.ROOT, and saw that the default groupingBy map is an unordered HashMap.
Open with
For the first map I would use the three-argument groupingBy: String::length as the classifier, TreeMap::new as the map factory so the lengths come out sorted, and Collectors.counting as the downstream.
Then, if they want more
That gives a Map of Integer to Long, for example 3 maps to 1 and 4 maps to 2. I would point out that counting returns Long, so if the API wants Integer counts I would use summingInt with a lambda returning one instead.
For the second map, I would first filter out empty strings, because charAt zero throws on an empty string, and lowercase each word with Locale.ROOT so case does not split groups and the result does not depend on the server's locale.
Then I sort the stream and group by charAt zero into a TreeMap with toList as the downstream. groupingBy keeps the encounter order inside each group, so sorted input gives alphabetical lists, like a maps to apple and avocado. An alternative that does not depend on the stream order is collectingAndThen with toList and a sort of each list.
I would also mention that without the TreeMap factory, groupingBy uses a HashMap today, which has no guaranteed order, so asking for sorted means passing a sorted map. And for real user-facing words I would consider a Collator for locale-aware sorting, and codePointAt instead of charAt if words can start with emoji.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Given List<String> words, use streams to produce a map from word length to the number of...": https://scrivio-interview-library.netlify.app/java/coding-problems/2b546f2d93/