Skip to content
Fix Code Error

Best way to convert an ArrayList to a string

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Solution

Java 8 introduces a String.join(separator, list) method; see Vitalii Federenko’s answer.

Before Java 8, using a loop to iterate over the ArrayList was 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:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

String listString = "";

for (String s : list)
{
    listString += s + "t";
}

System.out.println(listString);

In fact, a string concatenation is going to be just fine, as the javac compiler will optimize the string concatenation as a series of append operations on a StringBuilder anyway. Here’s a part of the disassembly of the bytecode from the for loop from the above program:

   61:  new #13; //class java/lang/StringBuilder
   64:  dup
   65:  invokespecial   #14; //Method java/lang/StringBuilder."<init>":()V
   68:  aload_2
   69:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   72:  aload   4
   74:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   77:  ldc #16; //String t
   79:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   82:  invokevirtual   #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;

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 StringBuilder is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit StringBuilder would 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 StringBuilder on 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 StringBuilder object outside of the for loop.

Rewriting to the above code to:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

StringBuilder sb = new StringBuilder();
for (String s : list)
{
    sb.append(s);
    sb.append("t");
}

System.out.println(sb.toString());

Will only instantiate the StringBuilder once outside of the loop, and only make the two calls to the append method inside the loop, as evidenced in this bytecode (which shows the instantiation of StringBuilder and the loop):

   // Instantiation of the StringBuilder outside loop:
   33:  new #8; //class java/lang/StringBuilder
   36:  dup
   37:  invokespecial   #9; //Method java/lang/StringBuilder."<init>":()V
   40:  astore_2

   // [snip a few lines for initializing the loop]
   // Loading the StringBuilder inside the loop, then append:
   66:  aload_2
   67:  aload   4
   69:  invokevirtual   #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   72:  pop
   73:  aload_2
   74:  ldc #15; //String t
   76:  invokevirtual   #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   79:  pop

So, indeed the hand optimization should be better performing, as the inside of the for loop is shorter and there is no need to instantiate a StringBuilder on each iteration.

Answered By: coobird

Related Articles

  • Form field border-radius is not working only on the…
  • Trouble with boxes appearing/hiding based on selection
  • How can I resolve Web Component Testing error?
  • Generating a drop down list of timezones with PHP
  • Active tab issue on page load HTML
  • When I'm testing a web app by JUnit and Mockito I…
  • Stacked Tabs in Bootstrap 3
  • Unable to run Robolectric and Espresso with a…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • ClassNotFoundException:…
  • Eclipse will not start and I haven't changed anything
  • Neither BindingResult nor plain target object for…
  • java IO Exception: Stream Closed
  • Jetpack Compose and Hilt Conflict
  • SQLException: No suitable Driver Found for…
  • SecurityException: Permission denied (missing…
  • Gradle error: Execution failed for task…
  • Examples of GoF Design Patterns in Java's core libraries
  • How can I make this v-tabs Vuetify.js component work?
  • SQL JOIN and different types of JOINs
  • SQL query return data from multiple tables
  • Can't access Eclipse marketplace
  • Requested bean is currently in creation: Is there an…
  • GLYPHICONS - bootstrap icon font hex value
  • How to show title in hover - css / jquery
  • Using enums in a spring entity
  • android studio 0.4.2: Gradle project sync failed error
  • Execution failed for task…
  • How to parse JSON file with Spring
  • Vue rendering order
  • org.gradle.api.tasks.TaskExecutionException:…
  • Adding Google Translate to a web site
  • How to format a phone number in a textfield
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Android Studio 4.2.1 NullPointer Exception on startup
  • JPA Hibernate Persistence exception…
  • Android- Error:Execution failed for task…
  • How to convert java.util.Date to java.sql.Date?
  • ClassNotFoundException thrown
  • Configure hibernate to connect to database via JNDI…
  • vue js cant understand keep alive
  • Could not install Gradle distribution from…
  • When tab is selected, show next tab.. if last tab…
  • How does PHP 'foreach' actually work?
  • Vaadin: Tabs are displayed in a really bizarre way -…
  • Dynamic tabs with user-click chosen components
  • "Non-resolvable parent POM: Could not transfer…
  • Error inflating class android.support.v7.widget.Toolbar?
  • SQL Server: Query fast, but slow from procedure
  • Vaadin Spring Boot - There was an exception while…
  • Launching Spring application Address already in use
  • How to add Typescript to a Nativescript-Vue project?
  • Is it possible to apply CSS to half of a character?
  • How do I install Java on Mac OSX allowing version switching?
  • Getting Dropwizard Client And Jersey/HTTP I/O Error…
  • hide select options using only css
  • data.table vs dplyr: can one do something well the…
  • Vuejs: Using keep-alive (Or something similar) on a slot
  • java.lang.RuntimeException: Unable to instantiate…
  • java.lang.ClassNotFoundException: HttpServletRequest
  • Plugin…
  • UnsatisfiedDependencyException: Error creating bean…
  • Eclipse fails to open .vue files in Web Page Editor
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • Vaadin Designer Tabs not correctly adding children…
  • Java ElasticSearch None of the configured nodes are…
  • How to obtain the start time and end time of a day?
  • nesting elements and dynamic content inside…
  • Spring Boot with ElasticSearch in Groovy: WebClient…
  • Javascript text animation not triggering
  • When to use LinkedList over ArrayList in Java?
  • Problems using Maven and SSL behind proxy
  • In Jquery show selected a value from the searched…
  • What is a stack trace, and how can I use it to debug…
  • How to make my custom tab component work with…
  • INNER JOIN vs LEFT JOIN performance in SQL Server
  • Spring Boot - Cannot determine embedded database…
  • What does "Could not find or load main class" mean?
  • Injection of autowired dependencies failed;
  • NullpointerException error while working with…
  • Failed to execute goal…
  • How to convert number to words in java
  • Address already in use: JVM_Bind
  • Ways to iterate over a list in Java
  • What's the difference between Instant and LocalDateTime?
  • Gradle: Execution failed for task ':processDebugManifest'
  • Eclipse - Run in Debug Mode fails
  • Spring schemaLocation fails when there is no…
  • Using querySelector to find nested elements inside a…
  • Polymer 1.0 paper-tabs addEventListener stops…
  • How to use Vuetify tabs with vue-router
  • How to show multiple select options when user select…
  • Why does C++ code for testing the Collatz conjecture…
  • Polymer: Binding paper-tabs to core-pages inside…
  • java.lang.NullPointerException: Attempt to invoke…
  • How to filter a RecyclerView with a SearchView
  • Multipart File Upload Using Spring Rest Template +…
  • How to fix Hibernate LazyInitializationException:…
  • What's causing my java.net.SocketException:…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to find if directory exists in Python

Next Post:

CSS selector for first element with class

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error