def repeat(str, n):
return str * n
If you want to generate a new string that repeats the contents of the string n times, you can write it in Python as in the example above. In other words, the *
operator has the function of repeating a character string, but when it comes to realizing the same thing in Java, I think that the following methods are often defined (null check etc. abridgement).
public static String repeat(String str, int n) {
var sb = new StringBuilder();
while(n-- > 0) sb.append(str);
return sb.toString();
}
It's true that this is fine, but it's a shame that you can write in one line in Python but not in Java (mystery). So I often think about how to write string repetitions simply in Java, but the first thing I personally think of is to use Stream
.
public static String repeat(String str, int n) {
return IntStream.range(0, n).mapToObj(i -> str).collect(Collectors.joining(""));
}
It's certainly one line, but I get the impression that it's written in a slightly tricky way to make it one line. In order to make it simpler, I came up with the following method while researching various things.
public static String repeat(String str, int n) {
return String.join("", Collections.nCopies(n, str));
}
It's shorter and simpler. I don't feel like doing tricky things to make it shorter. Since Collections.nCopies
generates a list, I would like to actively use it while paying attention to that.
It's not good to use Apache Commons Lang's StringUtils.repeat
(´ ・ ω ・ `)
Recommended Posts