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.
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.
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.
The Java ArrayList toString() method converts an arraylist into a String. Here, arraylist is an object of the ArrayList class.
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(", "));
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With