Is there any quick way of converting a String Array to a StringBuilder Array other than using a loop?
Say I have this string array:
String[] str = new String[] {"hi","hello"};
I need to create a StringBuilder array with the same literals.
Arrays.setAll() seems to be the simplest one, it may be shorter to type than a loop:
String[] str = new String[] {"hi","hello"};
StringBuilder[] sbs = new StringBuilder[str.length];
Arrays.setAll(sbs, i -> new StringBuilder(str[i]));
There is even parallelSetAll(), but for simply creating objects it would have to be a really long array to profit from parallelism I think.
You won't believe how it looks like on the inside:
public static <T> void setAll(T[] array, IntFunction<? extends T> generator) {
Objects.requireNonNull(generator);
for (int i = 0; i < array.length; i++)
array[i] = generator.apply(i);
}
(The parallel one uses IntStream.range().parallel().forEach())
String[] str = new String[] {"hi","hello"};
StringBuilder[] sbs=Arrays.stream(str)
.map(s->new StringBuilder(s))
//.collect(Collectors.toList()) // not needed, see comments
// of @RealSkeptic and @Holger
.toArray(StringBuilder[]::new);
So yes of course, it can be done without writing the single loop statement. Just in the background there will be two loops now, one for creating the I still would not call it particularly beautiful StringBuilders into a List, and one for converting it to an array. Andeither, especially when considering that a similar bunch of lines will be there too at the end, for the other direction.
for loop, doing everything in the body:
String[] str = new String[] {"hi","hello"};
for(int i = 0; i < str.length; i++) {
StringBuilder sb = new StringBuilder(str[i]);
...magic...
str[i] = sb.toString(); // or perhaps into a new array
}
Stream has its own toArray method which works exactly the same.StringBuilder[] sbs = Arrays.stream(str).map(StringBuilder::new).toArray(StringBuilder[]::new); In fact, prior to Java 11, .toArray(StringBuilder[]::new) only works with a Stream.
StringBuilder[]? Really? What for? If you want theString[]to be quickly converted to a singleStringdelimited by single whitespaces, dostring sentence = String.join(" ", str);...