Start learning free

LESSON 21 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in Java: Alphabetical Order with Collections.sort

Practice Read the full explanation

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), 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: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Copy the input into a fresh ArrayList, sort it with Collections.sort, then String.join.

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

STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in Java, explained

    Problem overview

    This is the first version of a small sort command. The method sortLines takes a List<String>, orders the lines ascending by character code, and returns them as one String with a \n between each two lines. Duplicates stay, and an empty list gives "".

    For ["banana", "apple", "cherry"] the answer is "apple\nbanana\ncherry". Printed, that is three lines: apple, banana, cherry.

    "By character code" means a plain comparison of the characters. Every uppercase ASCII letter has a smaller code than every lowercase one, so "Zebra" comes before "apple". An empty line has no characters, so it sorts before everything else.

    Approach: copy, sort, join

    Java already knows how to order strings. String implements Comparable, and its natural order compares characters one by one by code, which is the order this lesson asks for. So the work is three small moves:

    1. copy the input list, so the caller's list is left as it was;
    2. sort the copy;
    3. join the sorted lines with newlines.

    The copy matters because Collections.sort reorders its argument in place. If the method sorted lines itself, the caller's list would change as a side effect. And if the caller passed an immutable list such as List.of(...), sorting it would throw UnsupportedOperationException. A new ArrayList can always be sorted.

    Step by step

    1. Make the copy. new ArrayList<>(lines) builds a new list holding the same strings. Store it in sortedLines.
    2. Sort it in place with Collections.sort(sortedLines). It returns nothing, because the list itself is rearranged.
    3. Join and return. String.join("\n", sortedLines) puts its first argument between the strings of the list, so there is no newline after the last line.

    The solution in Java

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

    Details worth knowing:

    • Collections.sort returns void. Writing return Collections.sort(...) doesn't compile. Sort first, then use the list.
    • The sort is stable. Equal strings keep their relative order. For plain strings you can't tell the difference, but later versions of this tool sort by a key, where it matters.
    • The copy is shallow. Strings are immutable, so sharing them between the two lists is harmless.
    • Imports. List, ArrayList and Collections live in java.util.

    Complexity

    Time: O(n log n) comparisons for n lines, from the sort. Each comparison looks at characters until two lines differ, so long lines with a shared prefix make each comparison slower. Copying and joining are O(n) in the number of lines, plus the text itself.

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

    Edge cases and common mistakes

    • Case. ["apple", "Zebra", "", "apple", "Banana"] becomes "\nBanana\nZebra\napple\napple": the empty line first, then the capitals, then the lowercase words, with both copies of apple kept.
    • Empty list. [] gives "", because joining nothing gives an empty string.
    • Sorting the caller's list. Skipping the copy changes the input. With the copy, a list ["b", "a"] is still [b, a] after the call.
    • Expecting dictionary order. A case-insensitive order would put "apple" before "Zebra". The natural order of String doesn't do that, and this lesson wants the character-code order.

    Testing

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