Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert an ArrayList to a string

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.

like image 392
Juan Besa Avatar asked Mar 01 '09 02:03

Juan Besa


People also ask

How do you return an ArrayList to a String in Java?

add(3); return(numbers); } } public class T{ public static void main(String[] args){ Test t = new Test(); ArrayList<Integer> arr = t. myNumbers(); // You can catch the returned integer arraylist into an arraylist. } } I think you mean arr = t.

How do I convert a list to a String in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

Is there a toString for ArrayList?

The Java ArrayList toString() method converts an arraylist into a String. Here, arraylist is an object of the ArrayList class.


2 Answers

In Java 8 or later:

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

In case the list is not of type String, a joining collector can be used:

String listString = list.stream().map(Object::toString)                         .collect(Collectors.joining(", ")); 
like image 105
Vitalii Fedorenko Avatar answered Sep 17 '22 21:09

Vitalii Fedorenko


If you happen to be doing this on Android, there is a nice utility for this called TextUtils which has a .join(String delimiter, Iterable) method.

List<String> list = new ArrayList<String>(); list.add("Item 1"); list.add("Item 2"); String joined = TextUtils.join(", ", list); 

Obviously not much use outside of Android, but figured I'd add it to this thread...

like image 26
JJ Geewax Avatar answered Sep 18 '22 21:09

JJ Geewax