Learnitweb

Find the Shortest String in a List

Approach 1 — Using min with a Comparator

Optional<String> shortest = words.stream()
    .min(Comparator.comparingInt(String::length));

Approach 2 — Sorting and Taking First

Optional<String> shortest2 = words.stream()
    .sorted(Comparator.comparingInt(String::length))
    .findFirst();

Explanation:

  • min is O(n) and more efficient.
  • Sorting is O(n log n) but can be simpler in code for complex use cases.