Start learning free

LESSON 5 OF 68 · PROJECTS: COMMAND-LINE TOOLS

head v1 in Java: First 10 Lines with subList

Practice Read the full explanation

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

public String head(List<String> lines)

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Use List.subList(int from, int to) to grab the first 10 lines, but cap to at lines.size() when the list is shorter than 10. Then String.join("\n", subList).

Compute int end = Math.min(10, lines.size()), then call lines.subList(0, end).

The full solution:
class Solution {
    public String head(List<String> lines) {
        int end = Math.min(10, lines.size());
        return String.join("\n", lines.subList(0, end));
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Head V1 in Java, explained

    Problem overview

    This is the first version of a small model of the Unix head command. The method head(List<String> lines) returns the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, all of them are returned, and an empty list gives an empty string.

    For the 13 lines "a" to "m", the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj", which prints as the letters a to j, one per row. The letters k, l and m are dropped. The next version lets the caller choose the number of lines.

    Approach: cut the list, then join

    There are two jobs: pick the lines to keep, then glue them into one string. The second job is String.join("\n", ...), which puts the separator between elements and nothing after the last one. For the first job, lines.subList(0, end) gives the part of the list from index 0 up to, but not including, end.

    The only difficulty is choosing end. It should be 10, unless the list is shorter, and then it should be the list's size. That is the smaller of the two numbers, which Math.min computes. With 13 lines it gives 10, with 3 lines it gives 3, and with no lines it gives 0.

    Step by step

    1. Compute the end index. Declare int end = Math.min(10, lines.size()). It is never more than the number of lines, so the next call can't ask for lines that aren't there.
    2. Cut and join. Take lines.subList(0, end) and pass it to String.join("\n", ...). Return the result.

    The solution in Java

    class Solution {
        public String head(List<String> lines) {
            int end = Math.min(10, lines.size());
            return String.join("\n", lines.subList(0, end));
        }
    }
    

    The Java details worth a closer look:

    • The end index is exclusive. subList(0, 10) holds the elements at positions 0 to 9, which is ten of them. The start is inclusive and the end is not, so subList(0, end) always has exactly end elements.
    • The range must be valid. subList throws an exception when the end is larger than the size. Math.min is what prevents that here.
    • An empty list is fine. With no lines, end is 0, subList(0, 0) is an empty list, and joining an empty list gives "".
    • subList is a view. It doesn't copy the elements; it looks at the original list. That is fine here, because join reads it immediately, and the method never changes lines.
    • Math.min works on int values. Both arguments here are int (lines.size() returns an int), so no conversion is needed.

    Complexity

    Time: O(k + C), where k is the number of lines kept (at most 10) and C is their total number of characters. The sublist is created in constant time, and the join copies only the kept lines. Lines beyond the tenth are never touched.

    Space: O(C) for the returned string.

    Edge cases and common mistakes

    • Fewer than 10 lines. Writing lines.subList(0, 10) directly would throw for a short list. Capping with Math.min returns all the lines instead.
    • Exactly 10 and 11 lines. With 10 lines, all of them are returned. With 11, the last one is dropped.
    • Empty input. An empty list gives "", not an error.
    • A trailing newline. Appending "\n" after each line in a loop would leave one after the last line. String.join puts separators only between lines.

    Testing

    The results below come from running the solution:

    • The 13 lines a to m give "a\nb\nc\nd\ne\nf\ng\nh\ni\nj".
    • The 3 lines a, b, c give "a\nb\nc".
    • The 11 lines a to k give "a\nb\nc\nd\ne\nf\ng\nh\ni\nj".
    • An empty list 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