Start learning free

LESSON 602 OF 671 · PROJECTS: COMMAND-LINE TOOLS

cat v4 in Java: Concatenating Several Files with Nested Loops

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

public String concatCat(List<List<String>> allLines)

Example:

Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]]

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Build a flat List<String> with a nested loop, preserving order. Then return String.join("\n", flat).

List<String> flat = new ArrayList<>();
for (List<String> fileLines : allLines) {
    for (String line : fileLines) {
        flat.add(line);
    }
}
return String.join("\n", flat);


The full solution:
class Solution {
    public String concatCat(List<List<String>> allLines) {
        List<String> flat = new ArrayList<>();
        for (List<String> fileLines : allLines) {
            for (String line : fileLines) {
                flat.add(line);
            }
        }
        return String.join("\n", flat);
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in Java, explained

    Problem overview

    The real cat command accepts several files and prints them one after another. The fourth version models that with the method concatCat(List<List<String>> allLines). Each inner list is one "file", a list of lines. The method puts all the lines in order, first file first, and joins them with \n.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz", which prints as:

    hello
    world
    foo
    bar
    baz
    

    A file can be empty and adds no lines. If there are no files at all, the result is an empty string.

    Approach: flatten first, join once

    The input is a list of lists, but joining needs a single list of strings. So the method first flattens: it creates one empty list, flat, and copies every line of every file into it, preserving the order. After that, one call to String.join("\n", flat) produces the result, with a newline between lines and none after the last one.

    Flattening takes two nested loops: the outer one visits each file, the inner one visits each line of that file. An empty file never enters the inner loop, so it adds nothing, and no special case is needed. The same holds for an empty allLines: the outer loop doesn't run, flat stays empty, and joining an empty list gives "".

    Step by step

    1. Create the flat list. Declare List<String> flat and give it a new ArrayList. It will hold every line, with no lists inside.
    2. Loop over the files. A for-each loop with List<String> fileLines visits each file in order.
    3. Loop over the lines. Inside it, a second for-each loop with String line visits each line of that file.
    4. Add the line. flat.add(line) appends it, so lines keep the order of the files and of the lines inside each file.
    5. Join and return. After both loops, return String.join("\n", flat). It runs once, after every file has been read.

    The solution in Java

    class Solution {
        public String concatCat(List<List<String>> allLines) {
            List<String> flat = new ArrayList<>();
            for (List<String> fileLines : allLines) {
                for (String line : fileLines) {
                    flat.add(line);
                }
            }
            return String.join("\n", flat);
        }
    }
    

    The Java details worth a closer look:

    • Nested generics. List<List<String>> is a list whose elements are themselves lists of strings. The for-each loop's variable type, List<String>, must match the element type exactly.
    • The diamond. new ArrayList<>() lets the compiler fill in String from the declared type on the left.
    • For-each avoids indexes. Neither loop needs a position, so there is no i to get wrong and no size() to compare against.
    • The inputs are not changed. The method only reads allLines and the inner lists. All additions go into the new flat list.
    • String.join takes any list of strings. Besides flat, it works with any Iterable of character sequences, and it puts the separator only between elements.

    Complexity

    Time: O(L + C), where L is the number of lines in all files and C is the total number of characters. Each line is visited once and added to flat in constant time on average, and the join copies each character once.

    Space: O(L + C). The flat list holds a reference to each line, and the result string holds every character plus the separators.

    Edge cases and common mistakes

    • An empty file in the middle. [["a"], [], ["b"]] gives "a\nb". The empty file adds nothing, not even an extra newline.
    • No files, or only empty files. [] and [[], []] both give "".
    • Blank lines are lines. [[""], [""]] gives "\n": two lines, both empty, with one separator between them. An empty file contributes no lines, but a file holding one empty string contributes one.
    • Joining each file separately. Joining the lines of every file and then appending "\n" to each file would leave a trailing newline, and would produce a wrong separator for an empty file. Flattening first avoids both.
    • Passing the wrong thing to join. String.join("\n", allLines) doesn't compile for a List<List<String>>, because the elements aren't character sequences. That is why the flat list is built first.

    Testing

    The results below come from running the solution:

    • [["hello", "world"], ["foo", "bar", "baz"]] gives "hello\nworld\nfoo\nbar\nbaz".
    • [["a"], [], ["b"]] gives "a\nb".
    • [] gives "".
    • [[], []] gives "".
    • [[""], [""]] gives "\n".
    • [["z"]] gives "z".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free