How to solve the "repeatSeparator" problem without a loop in Java?

If you absolutely want to hide the loops in the implementation, you could do something like this:

public String repeatSeparator(String word, String separator, int count) {
    return IntStream.range(0, count)
        .mapToObj(i -> word)
        .collect(Collectors.joining(separator));
}

The code above generates the numbers between 0 and count-1, replaces each number with the given word and finally concatenates them with the given separator.

Note that this still uses loops, they're just hidden inside the streams. Worse still, this solution is almost certainly way less efficient than a naive StringBuilder+for solution.

Edit: A (potentially) simpler version of the same idea:

public String repeatSeparator(String word, String separator, int count) {
    return Stream.generate(() -> word)
        .limit(count)
        .collect(Collectors.joining(separator));
}

Create an infinite stream of the word, limit it to the given count, then concatenate them with the separator.


One liner using Java 11:

String repeatSeparator(String word, String sep, int count) {
    return (word + sep).repeat(count-1) + word;
}

One liner using Java 8:

String repeatSeparator(String word, String sep, int count) {
    return String.join(sep, Collections.nCopies(count, word));
}

Tags:

Java