basically I'd like to see if there is a compact lambda way of doing this:
int n = ...
String s = "";
for (int i = 0; i < n; i++) {
s += 'a';
}
The start is easy, then I'm lost:
IntStream.range(0, n). ??
basically I'd like to see if there is a compact lambda way of doing this:
int n = ...
String s = "";
for (int i = 0; i < n; i++) {
s += 'a';
}
The start is easy, then I'm lost:
IntStream.range(0, n). ??
This is better:
String s = Stream.generate(() -> "a").limit(n).collect(Collectors.joining());
It is very straightforward;
int n = 20;
System.out.println(IntStream.range(0, n).boxed().map(i -> "a").collect(Collectors.joining()));
Prints out;
aaaaaaaaaaaaaaaaaaaa
You have to do boxed()
to switch to a Integer
stream, then just map each number to a "a"
String, which will transform your stream of 1,2,3,4...
to a,a,a,a,a...
and finally join them.
Why use stream/lambda for this? Less efficient.
If you want a one-liner, try this instead:
String s = new String(new char[n]).replace('\0', 'a');