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
- Copy the input into a new
ArrayListcalledsortedLines, so the caller's list isn't reordered. - Sort the copy with
sortedLines.sort(...), passingComparator.comparingand a lambda that maps a line to its key: split at commas, take positionfield - 1. - Pass
-1as the second argument ofsplit, so empty pieces at the end of a line are kept. - 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
-1limit insplitmatters. By defaultsplit(",")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,,"throwsArrayIndexOutOfBoundsException, 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 tofield. - Type inference. The compiler works out that
lis aStringfrom the type ofsortedLines.sort, so no type is written on the lambda. splittakes a regular expression. A comma has no special meaning in one, so","works as a plain separator.- Imports.
List,ArrayListandComparatorare injava.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,,"]andfield = 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,"]andfield = 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
fieldinstead offield - 1reads 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"]andfield = 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"]withfield = 2gives"bob,25\nalice,30\ncarol,40".["alice,30", "bob,25", "carol,40"]withfield = 1gives"alice,30\nbob,25\ncarol,40".["x,b", "y,a", "z,b", "w,a"]withfield = 2gives"y,a\nw,a\nx,b\nz,b".["a,b,", "c,b,x", "d,b,"]withfield = 3gives"a,b,\nd,b,\nc,b,x".[]withfield = 1gives"".
