Java Streams learning path Level 1 This level · 19 of 25
Easy java streams

Sort strings by length with a tie-breaker

The 30 second answer

I sort with Comparator.comparingInt on String::length, and call reversed for longest first. Then I add thenComparing with natural order so words of the same length come out alphabetically instead of in whatever order they arrived. I use a method reference rather than a lambda, because with a lambda the compiler infers Object before reversed and the code does not compile.

Could you say this in an interview?
var words = List.of("pear", "fig", "banana", "kiwi", "apple", "date");

var shortestFirst = words.stream()
    .sorted(Comparator.comparingInt(String::length))
    .toList();
// [fig, pear, kiwi, date, apple, banana]

var longestFirst = words.stream()
    .sorted(Comparator.comparingInt(String::length).reversed()
        .thenComparing(Comparator.naturalOrder()))
    .toList();
// [banana, apple, date, kiwi, pear, fig]

Ties: sorted is stable for ordered streams, so without a tie-breaker equal-length words keep their input order (pear, kiwi, date above). Say that out loud, then add thenComparing if they want a deterministic order that does not depend on the input.

Compile trap: Comparator.comparingInt(s -> s.length()).reversed() does not compile. The lambda has no target type at the point where reversed() is called, so s is inferred as Object and javac reports that it cannot find length(). Use String::length, or wrap the whole comparator as Collections.reverseOrder(...). I checked this with javac 17.

Complexity: O(n log n) time and O(n) extra space, because sorted buffers the whole stream. To sort a mutable list in place, list.sort(sameComparator) avoids the stream.

Edge cases: an empty list returns an empty list. Null elements throw NullPointerException in String::length; wrap the comparator in Comparator.nullsLast(...) if nulls are allowed.

What interviewers listen for: reversed() applies to everything chained before it, so put it right after the key you want descending. They also listen for whether you mention stability and the tie-breaker without being asked.

Sources (2)
  1. Comparator (comparingInt, reversed, thenComparing, naturalOrder)docs.oracle.com
  2. Stream.sorted (stability for ordered streams)docs.oracle.com
Previous
Next