← Java from Scratch Lesson 71 of 88 · 10 XP

Sorting lists

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

List<String> words = new ArrayList<>(List.of("banana", "Apple", "cherry"));
Collections.sort(words);                               // the natural order: [Apple, banana, cherry]
words.sort(Comparator.reverseOrder());                 // descending
words.sort(String.CASE_INSENSITIVE_ORDER);             // ignoring case
words.sort(Comparator.comparingInt(String::length));   // by length (more in "Advanced sorting")
  • the natural order is set by the Comparable interface (the compareTo method): for numbers — by value, for strings — by character codes, which is why the capitals A–Z come before the lower-case letters;
  • sorting in Java is stable: equal elements keep their original order — this matters when sorting by several criteria;
  • under the hood it's TimSort (a hybrid of merge sort and insertion sort), O(n log n).

Task. Read words. Print them sorted: naturally, in descending order, ignoring case, and by length (with equal lengths — in the original order). Each variant on its own line, separated by spaces.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.