Suppose you have the string ‘qwe’ and you need to repeat string ‘n’ times. Here’s how to do it:
Using java 8 stream api
1 2 3 4 5 |
String newString = Collections.nCopies(3, "qwe").stream().collect(Collectors.joining("")); String newString = Stream.generate(() -> "qwe").limit(3).collect(Collectors.joining()); String newString = String.join("", Collections.nCopies(n, s)); |
Using String.format
1 2 3 4 |
String s = "qwe"; int n = 3; //this line print 'qweqweqwe' String newString = String.format("%0" + n + "d", 0).replace("0", s); |
Let us examine this example in more detail. Primitive types ( char[] , in this case) are instantiated with nulls “number of times”, then a String is created from the char[] , and the nulls are replaced() with the original string str.
Using StringBuilder and loop
And last but not least, you can use StringBuilder and loop
1 2 3 4 5 6 7 8 |
int n = 3; String in = "qwe"; StringBuilder b = new StringBuilder(n * in.length()); for (int i = 0; i < n; i += 1) { b.append(in); } String newString = b.toString(); |
Using third-party libraries
You could use Apache commons-lang (which has an impressive collection of handy string utilities):
1 |
String newString = StringUtils.repeat(3, "qwe"); |