In a "pretty print" function for a nested map, I need a simple indent function to prepend the needed space to my structure. I wanted a simple one-liner and the best I found was a 2 line solution. Ideally, I wanted this:
String indentSpace = new String(Arrays.fill(new char[indent], 0, indent-1, ' '));
That doesn't work because Arrays.fill is not 'fluent'; it returns void.
A literal translation of that expression is too verbose for my liking:
char[] chars = new char[indent];
Arrays.fill(chars , ' ');
String indentSpace = new String(chars);
Finally, I settled for a lack-lustre 2-line solution:
private final String indentSpace=" ";
...
String alternative = indentSpace.substring(0,indent % indentSpace.length());
This is minor nit-picking, but I remained curious on whether there's a more elegant solution. I recon that the last option might be a good choice performance-wise.
Any takes?
The following one-liner should work:
String indentSpace = new String(new char[indent]).replace('\0', ' ');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With