Sort a String array by length with a Comparator
Sort a String array by length with a Comparator
Answer
Arrays.sort(words, (a, b) -> Integer.compare(a.length(), b.length()));
Arrays.sort(T[], Comparator<T>) sorts object arrays in place. The lambda is a Comparator<String>; Integer.compare avoids the subtraction-overflow bug of `a.length() - b.length()`. The sort is stable, so equal-length words keep their original relative order.