Search code examples
javaarraysstringstringbuilder

Convert String array to StringBuilder array


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.


Solution

  • 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())


    Original answer
    No loops were harmed during the making of these lines:

    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 StringBuilders into a List, and one for converting it to an array. And I still would not call it particularly beautiful either, especially when considering that a similar bunch of lines will be there too at the end, for the other direction.


    If the modifications are independent, and the ends have to stay arrays, I would indeed go with a single, "classic" indexed 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
    }