Thursday, September 14, 2023

6 Ways to convert ArrayList to String in Java - Example Tutorial

Many times we need elements stored in ArrayList in a single String object, but in different format than toString() method of ArrayList provides. At times, you may need them separated by comma, other times by by a tab or new line character. How do you convert your ArrayList to String in Java? Well, even though standard JDK doesn't provide any utility method to do that, there are numerous way to do that out-of-the-box, I mean, without you writing your own method to do that conversion. In the past, I showed you how to convert a Collection to String in Java and in this article, we will take a look at some of them, but beware many of the methods require third party library, which means an extra dependency in your build path. If you don't mind that than you could save lot of time reusing tried and tested code. 

Remember, "good coder code but great coder re-use".

6 Examples to Convert ArrayList to String in Java. 

Here is a 6 easy ways to convert a given ArrayList to String in Java. I have shared both JDK and Third party libraries which you can use to do this task easily in Java. 

1. Using JDK 8 StringJoiner

Java 8 has added a new class called StringJoiner which can be used to join String from arrays and Collection. It also added a convenient join() method on String class which you can use for more convenient as shown below :

String listString = String.join(", ", list);

Remember, the list must be list of String. In case the list is not of type String, you can use use a joining collector as shown below :
String listString = list.stream()
                  .map(Object::toString)
                  .collect(Collectors.joining(", "));

This is actually the best way to convert ArrayList to String because you don't need a third party library but problem is its only available from Java 8 and most of production code is still running on lower version. 


2. Using Apache Commons StringUtils

IF you are not using Apache commons library than its good time to add it into your build path. It provide several useful utility e.g methods to check if String is null or empty, converting list to array and others. It also provides a method to convert an ArrayList to comma separated String as shown below :

StringUtils.join(list, char separator)

join is overloaded to support different types e.g. primitive types, primitive arrays, objects and object array. The method we are using is nothing but accepts a Iterable and since ArrayList implements Iterable interface, we can use this method to join elements on ArrayList as delimited String.

This method is also null safe and null objects or empty strings within the iteration are represented by empty strings.

 

3. Using Google Guava Joiner

Google Guava is one of the famous general purpose library which deserve a place in every Java project. It provides common utility classes which can make your code simpler and easier to read, write, and test.  

Here is an example of Google Guava's Joiner class which can be used to convert a List to String in Java. 

String joined = Joiner.on("\t").join(list);

Though, you need to download and add Google Guava JAR in your Java classpath to make use of this method. Alternatively, if you are using Maven to build your project then you can also add Google Guava depending in your Maven project (pom.xml) and Maven will take care of adding them into classpath. 

4. Using SpringFramework StringUtils

Spring Framework also provides a class called StringUtils, which can be used to create a comma separated String from ArrayList.

public static String collectionToDelimitedString(Collection coll, String delim)

This method is also overloaded to add a prefix and suffix as well. BTW, this method is not part of Spring's public API and meant to be used by Spring developers for framework work. 


5. Android's TextUtils

Android provides a text utility class called TextUtils which has a join(String delimiter, Iterable) method, you can use this to convert ArrayList to String because ArrayList method implements Iterable interface 

String joined = TextUtils.join(", ", list);

Remark : This method will only work if you are coding for Android platform. TextUtils class is not from standard JDK but from android.text package. You can use this method to convert not only ArrayList of String but also ArrayList of any object. 



5 Brute force (write your own method)

It's simple to write, just loop over the ArrayList and then append each element into an empty StringBuilder or use a delimiter depending upon your requirement. 

char delimiter = ',';
StringBuilder result  = new StringBuilder("");
for (String object: listOfObject){
     result.append(object).append(delimeter);
}

Remark : Writing your own code is best and quick way around but you need to spend time on testing. If its just one off way than it make sense to code but you would find doing it again and again, hence either you create your own StringUtils class or use the one provided by open source libraries like commons or guava.

Here is an nice summary of all the 6 ways to convert an ArrayList or List to String in Java

6 Ways to convert ArrayList to String in Java - Example Tutorial



That's all about how to convert ArrayList to String in Java. I have showed not one or two but 6 different ways to convert an ArrayList to String in Java. You can use any of the two methods to convert a given ArrayList to String in Java depending upon your situation and liking. 

For example, if your project is not using any third party library then using JDK 8 StringJoiner is the best way to accomplish this task. Similarly, if your code is running on Java 7 or below then using one of the third party library library like Apache Commons or Google Guava is the best solution. 

Also, what is your favorite way to convert ArrayList to String in Java? By using String Joiner, Apache StringUtils, Spring Framework Utility method or writing your own code? Let me know in comments. 

1 comment:

  1. I always do copy paste? is that mean I am a greatest coder ever?

    ReplyDelete