Learnitweb

Find the Longest String in a List

Approach 1 — Using max with a Comparator

Optional<String> longest = words.stream()
    .max(Comparator.comparingInt(String::length));

Approach 2 — Using reduce Pairwise

Optional<String> longest2 = words.stream()
    .reduce((a, b) -> a.length() >= b.length() ? a : b);

Explanation:

  • max is readable and efficient.
  • reduce demonstrates functional programming by comparing elements pairwise.