I have an ArrayList that I want to output completely as a String. Essentially I want to output it in order using the toString of each element separated by tabs. Is there any fast way to do this? You could loop through it (or remove each element) and concatenate it to a String but I think this will be very slow.
I have an ArrayList that I want to output completely as a String. Essentially
Share
Java 8 introduces a
String.join(separator, list)method; see Vitalii Federenko’s answer.Before Java 8, using a loop to iterate over the
ArrayListwas the only option:DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead:
In fact, a string concatenation is going to be just fine, as the
javaccompiler will optimize the string concatenation as a series ofappendoperations on aStringBuilderanyway. Here’s a part of the disassembly of the bytecode from theforloop from the above program:As can be seen, the compiler optimizes that loop by using a
StringBuilder, so performance shouldn’t be a big concern.(OK, on second glance, the
StringBuilderis being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicitStringBuilderwould probably yield better performance.)In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.
Edit: As pointed out in the comments, the above compiler optimization is indeed creating a new instance of
StringBuilderon each iteration. (Which I have noted previously.)The most optimized technique to use will be the response by Paul Tomblin, as it only instantiates a single
StringBuilderobject outside of theforloop.Rewriting to the above code to:
Will only instantiate the
StringBuilderonce outside of the loop, and only make the two calls to theappendmethod inside the loop, as evidenced in this bytecode (which shows the instantiation ofStringBuilderand the loop):So, indeed the hand optimization should be better performing, as the inside of the
forloop is shorter and there is no need to instantiate aStringBuilderon each iteration.