Start learning free

LESSON 620 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in Java: Reverse Order with Collections.reverseOrder

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

public String sortLines(List<String> lines)

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Pass Collections.reverseOrder() as the second argument to Collections.sort.

The full solution:
class Solution {
    public String sortLines(List<String> lines) {
        List<String> sortedLines = new ArrayList<>(lines);
        Collections.sort(sortedLines, Collections.reverseOrder());
        return String.join("\n", sortedLines);
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in Java, explained

    Problem overview

    The second version of the sort tool adds the reverse flag, -r. The method sortLines still takes a List<String> and returns one String, but now the lines come out in descending order by character code, joined by \n. Duplicates stay, and an empty list gives "".

    For ["banana", "apple", "cherry"] the answer is "cherry\nbanana\napple". Because the order is the exact opposite of version 1, lowercase letters now come before uppercase ones, and an empty line comes last.

    Approach: the same pipeline with a different comparator

    Version 1 relied on the natural order of String. Reverse order needs a different rule, and in Java a rule for ordering is a Comparator. Collections.reverseOrder() returns a comparator that flips the natural order, so the biggest element sorts first.

    The rest is unchanged: copy the list so the caller's list is left alone, sort the copy, then join. A tempting alternative is to sort ascending and read the list backwards. A comparator is shorter, and it keeps the sorting rule in one place.

    What a comparator does

    A Comparator<String> has one job: given two strings x and y, return a negative number if x should come first, a positive number if y should, and 0 if they tie. The natural order is x.compareTo(y), and reversing it means swapping the operands: y.compareTo(x). For example "b".compareTo("a") is 1, "a".compareTo("b") is -1 and "a".compareTo("a") is 0. The sort calls the comparator on pairs of lines and arranges the list so that every answer agrees.

    Three spellings give the same order for the lines ["apple", "Zebra", "", "apple", "Banana"]: Collections.sort(list, Collections.reverseOrder()), list.sort(Comparator.reverseOrder()) and list.sort((x, y) -> y.compareTo(x)). The lesson uses the first, and the other two are worth recognising when you read other code.

    Step by step

    1. Copy the input into a new ArrayList called sortedLines, so sorting doesn't touch the caller's list.
    2. Sort it with a second argument. Collections.sort(sortedLines, Collections.reverseOrder()) sorts the list in place using the reversed natural order.
    3. Join with newlines using String.join("\n", sortedLines) and return the result.

    The solution in Java

    class Solution {
        public String sortLines(List<String> lines) {
            List<String> sortedLines = new ArrayList<>(lines);
            Collections.sort(sortedLines, Collections.reverseOrder());
            return String.join("\n", sortedLines);
        }
    }
    

    Details worth knowing:

    • Collections.sort(list, comparator) is the two-argument form of the method from version 1. The comparator replaces the natural order for this one call.
    • reverseOrder() is generic. Java infers the element type from the list, so you don't write it out.
    • Equal strings stay in their original order, because the sort is stable. Reversing the comparator doesn't reverse the order of equal elements.
    • Imports. List, ArrayList and Collections are in java.util.

    Complexity

    Time: O(n log n) comparisons for n lines. The reversed comparator costs the same as the natural one. Copying and joining are linear.

    Space: O(n). The copy holds one reference per line, and the output string holds the text.

    Edge cases and common mistakes

    • Mixed case. ["apple", "Zebra", "", "apple", "Banana"] becomes "apple\napple\nZebra\nBanana\n". The empty line is last, so the result ends with a newline: that is the separator before an empty final line, not an extra one.
    • Empty list. [] gives "".
    • Forgetting the comparator. Collections.sort(sortedLines) alone gives the ascending order of version 1.
    • Reversing with Collections.reverse after sorting. That also works, but it takes a second pass. Passing the comparator does both in one call.
    • Sorting the original list. Without the copy, the caller's list changes, and an immutable list such as List.of(...) throws UnsupportedOperationException.

    Testing

    • ["banana", "apple", "cherry"] gives "cherry\nbanana\napple".
    • ["apple", "Zebra", "", "apple", "Banana"] gives "apple\napple\nZebra\nBanana\n".
    • [] gives "".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free