Start learning free

LESSON 622 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in Java: Stable Sort by a Key Column

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

public String sortLines(List<String> lines, int field)

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

List.sort(Comparator) uses a stable sort. The -1 limit keeps empty trailing fields ("a,b," has three fields). Pass Comparator.comparing(l -> l.split(",", -1)[field - 1]).

The full solution:
class Solution {
    public String sortLines(List<String> lines, int field) {
        List<String> sortedLines = new ArrayList<>(lines);
        sortedLines.sort(Comparator.comparing(l -> l.split(",", -1)[field - 1]));
        return String.join("\n", sortedLines);
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in Java, explained

    Problem overview

    The fourth version of the sort tool adds -k, sorting by one column. Each line is comma-separated and has at least field fields, and a field may be empty, as in "a,,c". The method sortLines(List<String> lines, int field) sorts the lines stably by the value in the 1-indexed column field, comparing those values as strings by character code. It returns the original lines joined by \n, and an empty list gives "".

    For field = 2 and ["alice,30", "bob,25", "carol,40"] the keys are "30", "25" and "40", so the answer is "bob,25\nalice,30\ncarol,40". With field = 1 the same list stays in the order alice, bob, carol.

    Two points shape the solution. Keys are compared as text, so "10" sorts before "9". And the sort must be stable: lines whose keys are equal stay in their input order.

    Approach: sort the lines by a key function

    Each line has a key, the text of its chosen column. Comparator.comparing builds a comparator from a function that extracts the key, and it orders lines by comparing their keys with the natural order of String. That is exactly the character-code order the lesson wants.

    The key function splits the line at commas and takes one piece. Fields count from 1, while positions in an array count from 0, so field 2 is the piece at position 1: the index is field - 1.

    The lesson uses the list's own sort method. List.sort is stable, so lines with equal keys keep their original relative order, with no extra tie-breaking code. For ["x,b", "y,a", "z,b", "w,a"] and field = 2 the result is "y,a\nw,a\nx,b\nz,b": y before w and x before z, as in the input.

    Step by step

    1. Copy the input into a new ArrayList called sortedLines, so the caller's list isn't reordered.
    2. Sort the copy with sortedLines.sort(...), passing Comparator.comparing and a lambda that maps a line to its key: split at commas, take position field - 1.
    3. Pass -1 as the second argument of split, so empty pieces at the end of a line are kept.
    4. Join with newlines using String.join("\n", sortedLines) and return the result.

    The solution in Java

    class Solution {
        public String sortLines(List<String> lines, int field) {
            List<String> sortedLines = new ArrayList<>(lines);
            sortedLines.sort(Comparator.comparing(l -> l.split(",", -1)[field - 1]));
            return String.join("\n", sortedLines);
        }
    }
    

    Details worth knowing:

    • The -1 limit in split matters. By default split(",") drops trailing empty strings. "a,b,,".split(",") gives [a, b], while "a,b,,".split(",", -1) gives [a, b, , ], four pieces. Without the -1, asking for position 2 of "a,b,," throws ArrayIndexOutOfBoundsException, although the line has four fields. Empty fields in the middle, as in "a,,c", are kept either way.
    • The lambda captures field. A lambda can use a local variable or parameter only if it is never reassigned (effectively final), and the method never assigns to field.
    • Type inference. The compiler works out that l is a String from the type of sortedLines.sort, so no type is written on the lambda.
    • split takes a regular expression. A comma has no special meaning in one, so "," works as a plain separator.
    • Imports. List, ArrayList and Comparator are in java.util.

    Complexity

    Time: O(n log n) comparisons for n lines, and each comparison splits two lines, which costs time proportional to their length. The key isn't cached, so a line gets split every time it takes part in a comparison.

    Space: O(n). The copy holds one reference per line. Each split creates short-lived arrays, but only for the lines being compared at that moment.

    Edge cases and common mistakes

    • Empty fields. For ["a,,c", "b,x,c", "c,,"] and field = 2, the keys are "", "x" and "". The result is "a,,c\nc,,\nb,x,c": the empty keys sort first, in input order.
    • Trailing empty field. For ["a,b,", "c,b,x", "d,b,"] and field = 3, the keys are "", "x" and "", and the result is "a,b,\nd,b,\nc,b,x". This is the case that needs -1.
    • Off by one. Using field instead of field - 1 reads the wrong column, and for the last field it runs past the end of the array.
    • Numbers sort as text. For ["a,10", "b,9"] and field = 2, the keys "10" and "9" compare as text, so "a,10" stays first. A numeric column needs the numeric comparison of version 3.
    • Empty list. [] gives "", and the key function is never called.

    Testing

    • ["alice,30", "bob,25", "carol,40"] with field = 2 gives "bob,25\nalice,30\ncarol,40".
    • ["alice,30", "bob,25", "carol,40"] with field = 1 gives "alice,30\nbob,25\ncarol,40".
    • ["x,b", "y,a", "z,b", "w,a"] with field = 2 gives "y,a\nw,a\nx,b\nz,b".
    • ["a,b,", "c,b,x", "d,b,"] with field = 3 gives "a,b,\nd,b,\nc,b,x".
    • [] with field = 1 gives "".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free