~/ 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/4921f4ce-0cf6-45be-82ed-9433d4ccdf22/flashcard utf-8 LF