~/ learn/ comp-308/ cards/ Arrays, Collections & Containers
1 of 30

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.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/96c52b3f-6ceb-4c51-8d75-96ab8087d04e/flashcard utf-8 LF