~/ learn/ comp-308/ cards/ Arrays in depth
1 of 5

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/27f5163f-390e-4c37-893d-a9e195435bba/flashcard utf-8 LF