Start learning free

LESSON 23 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in Java: Numeric Order with Comparator.comparingInt

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

public String sortLines(List<String> lines)

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Pass Comparator.comparingInt(Integer::parseInt) to Collections.sort. It converts each string to int for comparison while leaving the strings themselves unchanged.

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

STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in Java, explained

    Problem overview

    The third version of the sort tool adds -n, numeric sorting. Each line is the text of a 32-bit integer: an optional leading -, no +, and leading zeros such as "007" allowed. The method sortLines sorts the lines by their numeric value, ascending, and returns the original strings joined by \n. Lines with the same value keep their original relative order. An empty list gives "".

    For ["100", "20", "3", "10"] the answer is "3\n10\n20\n100".

    Plain string order gets this wrong. Text is compared one character at a time, so "100" comes before "20" because '1' is smaller than '2'. The same four lines sorted as text come out as 10, 100, 20, 3. The sort has to compare numbers while the list keeps holding strings.

    Approach: sort strings with a comparator that parses them

    You don't need to convert the list to integers and back. Converting would lose the original text: "007" would become 7, and the answer must still say "007". Instead the strings stay in the list, and a comparator decides which of two lines is smaller by parsing both into int values.

    Comparator.comparingInt builds such a comparator from a function that maps each element to an int. The function here is Integer::parseInt, a method reference to the method that turns a string into an int. The comparator parses two lines, compares the two numbers, and the sort arranges the list accordingly.

    The sort used by Collections.sort is stable, so lines with equal numeric values stay in their original order. "007" and "7" both parse to 7, and whichever came first in the input stays first in the output.

    Step by step

    1. Copy the input into a new ArrayList called sortedLines, so the caller's list isn't reordered.
    2. Sort with a numeric comparator. Pass Comparator.comparingInt(Integer::parseInt) as the second argument of Collections.sort, so lines are compared by number instead of by characters.
    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, Comparator.comparingInt(Integer::parseInt));
            return String.join("\n", sortedLines);
        }
    }
    

    Details worth knowing:

    • Integer::parseInt accepts the lesson's formats. A leading - is fine, and so are leading zeros: "007" parses as 7. A line that isn't a valid int, such as "x", makes the sort throw NumberFormatException.
    • The comparator returns an int comparison, not a difference. comparingInt compares the two keys with Integer.compare. Writing your own comparator as Integer.parseInt(a) - Integer.parseInt(b) is a classic bug: the subtraction can overflow. For ["2147483647", "-2147483648", "0"] that version returns 2147483647 0 -2147483648, which is not sorted, while comparingInt returns -2147483648 0 2147483647.
    • Method references. Integer::parseInt is shorthand for the lambda s -> Integer.parseInt(s).
    • Imports. List, ArrayList, Collections and Comparator are in java.util.

    Complexity

    Time: O(n log n) comparisons for n lines. Each comparison parses two short strings, which takes time proportional to their length (at most about 11 characters for a 32-bit integer), so the parsing adds only a constant factor. The key is recomputed at each comparison and not cached.

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

    Edge cases and common mistakes

    • Negative numbers. ["-5", "007", "7", "-12", "0", "2147483647", "-2147483648"] gives "-2147483648\n-12\n-5\n0\n007\n7\n2147483647".
    • Equal values written differently. ["7", "007", "07"] stays "7\n007\n07", and ["007", "7", "07"] stays "007\n7\n07". The sort never compares the text of tied lines, and the output keeps the original strings.
    • Sorting text. Collections.sort(sortedLines) with no comparator gives the text order of version 1, which is wrong here.
    • Parsing into a new list. If you convert to integers and back, leading zeros disappear and "007" comes back as "7".
    • Empty list. [] gives "", and the comparator is never called.

    Testing

    • ["100", "20", "3", "10"] gives "3\n10\n20\n100".
    • ["-5", "007", "7", "-12", "0", "2147483647", "-2147483648"] gives "-2147483648\n-12\n-5\n0\n007\n7\n2147483647".
    • ["7", "007", "07"] gives "7\n007\n07".
    • [] 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