352

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.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Juan Besa
  • 4,401
  • 5
  • 24
  • 25
  • 4
    _or remove each element_ Be careful, removing elements from an ArrayList list is a big NO-NO, as your "loop" will take quadratic time due to shifting elements (provided that you loop from first to last element). – Dimitry K Feb 03 '14 at 11:19
  • Same for collections: http://stackoverflow.com/questions/395401/printing-java-collections-nicely-tostring-doesnt-return-pretty-output – Ciro Santilli OurBigBook.com Mar 02 '15 at 10:56

27 Answers27

1184

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(", "));
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
  • 194
    I can't believe it took until Java 8 to add this. – Paul Aug 06 '14 at 15:02
  • 58
    This answer should be up-voted more! No hacks, no libraries & no loops. – Songo Aug 11 '14 at 18:56
  • 5
    this doesn't work for what the OP said. String.join takes as second argument Iterable extends CharSequence>. So it works if you have a List that you want to display, but if you have List it will *not* call toString() in it as wanted by the OP – Hilikus Aug 22 '14 at 22:30
  • I tested other code above but it did not work. When I try your solution, it works. Thank you. – sg552 Nov 11 '15 at 10:07
  • 3
    Why the hell this is not the first (and accepted) answer.. I always have to scroll down until I know it's there.. elegant and concise – Jack Feb 24 '17 at 15:08
  • 3
    Requires Android API 26+ – Arsen Sench Aug 28 '17 at 08:24
  • 2
    @Jack because Java 8 wasn't out yet when the other answer was accepted in 2009. – Albert Hendriks Mar 29 '18 at 12:38
  • In the second scenario (using `Collectors.joining`), what happens if the list is empty? Do you back an empty string or null? – ArtOfWarfare Jun 25 '18 at 15:11
  • @ArtOfWarfare in case of empty list for the second scenario stream return an empty String value – Oleg Ushakov Sep 13 '18 at 14:08
  • 1
    @Downhillski, where did you find that the order of the items from an ArrayList is not guaranteed? I found the opposite description on the docs, i.e.: if the stream source is ordered, the result will always be ordered. Documentation link: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html – Rafael Miquelino Oct 15 '19 at 22:23
  • @RafaelMiquelino, I was mistaken. the stream will honor whatever the order of the source. In this case, `ArrayList` is guaranteed to be ordered`. – Downhillski Oct 16 '19 at 14:48
  • In terms of performance, is this answer better than the accepted answer ? For example : Is ".stream().map().collect(.joining())" is faster that a simple loop with a StringBuilder.append( .toString()) ? – CtrlX Feb 14 '20 at 08:23
  • String listString = String.join(", ", list); will give values with comma separated string. If you want to remove comma, you can try this. listString.replace(", ", ""); Make sure you are not missing first parameter it is a combination of comma and space. Best luck!!! – Aamer Jun 21 '22 at 08:14
  • Not that `List.of("23535", "12414").stream().map(Object::toString).collect(Collectors.joining(", "))` gives *23535, 12414*. Which might be desired in some cases, but otherwise you would need at least the double quotes (for making JSONArrays for example): *"23535", "12414"*. I am using a `StringBuilder` for this. – BairDev Sep 14 '22 at 16:17
426

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...

JJ Geewax
  • 10,342
  • 1
  • 37
  • 49
  • What about if my List contains custom Class? Like If I've List, where PatientDetails is my bean class which solely contains getters and setters. I tried the above logic but getting classCastException as well as I've to cast it in compile time with (List). What according you to be the best possible solution? – YuDroid Jun 15 '12 at 14:23
  • 1
    Since `TextUtils.join` takes an `Object[]`, I'd assume that it's calling `toString()` on each token. Does `PatientDetails` implement `toString()`? If that doesn't solve the problem, you may be stuck doing something with the `Separator` class. – JJ Geewax Jun 15 '12 at 19:32
  • `public static String join(CharSequence delimiter, Iterable tokens)` Using raw type in a new library is really a fail on Google's side. Especially when it could have easily been generified to `public static String join(CharSequence delimiter, Iterable tokens)`. – Natix Oct 29 '13 at 09:34
  • 6
    `org.apache.lang3.StringUtils` does virtually the same, so your answer was absolutely of much use to me outside of Android :) – avalancha May 23 '14 at 13:28
  • Is there any way to make this work with \n as the delimiter? From testing, it doesn't seem to add a new line, it just leaves a single space. – cnfw Jun 30 '15 at 14:17
  • @avalancha - the class name is `org.apache.commons.lang3.StringUtils` . You missed a "commons" there. – Cheeso Feb 16 '16 at 17:27
  • 2
    The popularity of this answer (currently the highest voted one) shows you that many java questions stem from Android development – Amr H. Abd Elmajeed Mar 13 '16 at 22:49
381

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.

mic
  • 1,190
  • 1
  • 17
  • 29
coobird
  • 159,216
  • 35
  • 211
  • 226
  • Thanks for your answer. I didn't realize the compiler would probably optimize it! – Juan Besa Mar 01 '09 at 03:18
  • @Juan Besa: Although I've heard of this optimization in the past, this was the first time I actually tried to check if it really happens (by actually looking at the bytecode), so it was a learning opportunity for me as well :) – coobird Mar 01 '09 at 03:23
  • 12
    Consider using a StringBuilder class instead of just appending strings, for performance reasons. – Jeremy Mar 01 '09 at 03:38
  • 6
    THe compiler will optimize the string concatenation but you will be creating a new StringBuilder object each time the loop is executed. – Pedro Henriques Mar 01 '09 at 03:43
  • 1
    I agree. I'd go with the StringBuilder too, for performance reasons. – John Ellinwood Mar 01 '09 at 05:27
  • 4
    -1 for the use of +=, in this case it is a performance killer. Always use StringBuilder for repeated appending to a string. – starblue Mar 01 '09 at 10:37
  • 11
    This solution adds an extra "\t" at the end of the string which is often undesired, especially when you want to create a comma separated list or similar. I think the other solutions posted here, using Apache Commons or Guava, are superior. – Peter Goetz Apr 19 '12 at 09:52
  • if you want to print it in line Arrays.toString(list.toArray()) – Defuera Sep 03 '14 at 16:01
  • This is one of the better examples of the flaws of SO's voting system I've seen: 118 votes for a wrong answer. – Glenn Maynard Mar 23 '15 at 18:31
  • I am trying to convert an ArrayList to string in a project of mine. I was able to get the string, but it seems like there is an extra space between the characters. Does anyone know how to fix this? – LUKER Apr 16 '16 at 04:04
  • 3
    This is not the best answer. Look below at Vitalii for `Java` or Geewax for `Android` – Gibolt Mar 10 '18 at 22:32
256

Download the Apache Commons Lang and use the method

 StringUtils.join(list)

 StringUtils.join(list, ", ") // 2nd param is the separator.

You can implement it by yourself, of course, but their code is fully tested and is probably the best possible implementation.

I am a big fan of the Apache Commons library and I also think it's a great addition to the Java Standard Library.

Ravi Wallau
  • 10,416
  • 2
  • 25
  • 34
  • 66
    Unfortunately, the denizens of SO prefer to reinvent the wheel. – skaffman Jul 29 '09 at 07:14
  • 34
    Also in Apache Commons Lang. Usage would look like `StringUtils.join(list.toArray(),"\t")` – Muhd Mar 24 '11 at 05:14
  • 37
    This particular wheel is hardly worth an extra dependency. – Seva Alekseyev Feb 06 '12 at 18:46
  • 25
    @SevaAlekseyev I think that's debatable. If you add this dependency right away you will make use of its classes much more often than not. Instead of using "if string != null && string.trim() != "" you will use StringUtils.isNotEmpty... You will use ObjectUtils.equals() so that you don't have to check for null everywhere. But if you wait for the one dependency that justifies using these libraries, you might never actually use them. – Ravi Wallau Feb 06 '12 at 20:47
  • 7
    It's also nice that it won't add an additional tab at the end! – keuleJ Aug 09 '12 at 17:05
  • Minor mod to Ravi's comment: StringUtils.isNotBlank() trims whitespace. StringUtil.isNotEmpty() doesn't. –  Mar 09 '13 at 23:35
  • 3
    As an aside, with Apache Commons 3, it's not necessary to convert the list to an array. Just use: `StringUtils.join(list, "\t")`. – Kat Jul 25 '14 at 17:12
  • We can use `String.join(",", arrayList)` to convert the ArrayList into a single string and use delimiter to separate the array list values. No need to use another library. And if you don't want delimiter use `String.join("", arrayList);` – Swathi May 23 '18 at 01:12
  • @Swathi Note, `String.join` was added in Java 8, so it might not be available in your environment. for example, Android. – Joshua Pinter Dec 06 '18 at 00:01
  • Since Apache Jakarta is not more alive, I suggest to update this answer with reference to Apache Common 3. This is answer is still useful for code using JDK < 8. – рüффп Mar 11 '19 at 08:38
  • It's amazing how many things that should be in the language's core API are in the Apache Commons Lang instead. – haslo Jul 23 '19 at 08:20
141

This is a pretty old question, but I figure I might as well add a more modern answer - use the Joiner class from Guava:

String joined = Joiner.on("\t").join(list);
Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
94

Changing List to a readable and meaningful String is really a common question that every one may encounter.

Case 1. If you have apache's StringUtils in your class path (as from rogerdpack and Ravi Wallau):

import org.apache.commons.lang3.StringUtils;
String str = StringUtils.join(myList);

Case 2 . If you only want to use ways from JDK(7):

import java.util.Arrays;
String str = Arrays.toString(myList.toArray()); 

Just never build wheels by yourself, dont use loop for this one-line task.

Dimitri Hautot
  • 438
  • 5
  • 12
Sheng.W
  • 2,190
  • 16
  • 8
  • 1
    I didn't notice your Case 2 solution before posting my own. Yours is actually much better and saves the extra step. I would definitely recommend it over some of the answers that seem to require extra tools. – Elliander Sep 24 '15 at 20:32
  • 6
    `Arrays.toString(myList.toArray())` - the easiest and the most straightforward solution – Ondrej Bozek Aug 16 '16 at 07:09
  • I think this should be considered as the best and most efficient solution – Morey Jun 10 '19 at 21:21
  • `Arrays.toString(list.toArray())` is easy to write, but highly inefficient. – Matthieu Sep 15 '19 at 09:30
66

If you were looking for a quick one-liner, as of Java 5 you can do this:

myList.toString().replaceAll("\\[|\\]", "").replaceAll(", ","\t")

Additionally, if your purpose is just to print out the contents and are less concerned about the "\t", you can simply do this:

myList.toString()

which returns a string like

[str1, str2, str3]

If you have an Array (not ArrayList) then you can accomplish the same like this:

 Arrays.toString(myList).replaceAll("\\[|\\]", "").replaceAll(", ","\t")
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Ken Shih
  • 733
  • 5
  • 5
  • 3
    I think this is actually more efficient that the methods posted above. Such a shame it's shown on the bottom. It might not be elegant but I strongly believe your solution runs O(n) while the others theoretically run in O(n^2)(since Java Strings are immutable you basically create a new String on every merge, and it becomes worse as the resulting String becomes larger) – user3790827 Apr 15 '16 at 09:09
  • If your text is very large you end up eating your computers resources. – user3790827 Apr 15 '16 at 09:11
  • This method is 7-8 times more slower than using StringBuilder. – Zoka Nov 08 '16 at 13:03
  • @user3790827 You are looking at a very superficial level. If I tell you to search for a person in `m` households in `n` cities in `x` states, you would say it's `O(mnx)` or `O(n^3)`, but I can rephrase it to say "look for this person in this country," and you would immediately tell me `O(n)`. On top of that, all algorithms here are generally `O(n)`, there is no looping *within* a loop. – Jai Dec 11 '17 at 01:19
38

Loop through it and call toString. There isn't a magic way, and if there were, what do you think it would be doing under the covers other than looping through it? About the only micro-optimization would be to use StringBuilder instead of String, and even that isn't a huge win - concatenating strings turns into StringBuilder under the covers, but at least if you write it that way you can see what's going on.

StringBuilder out = new StringBuilder();
for (Object o : list)
{
  out.append(o.toString());
  out.append("\t");
}
return out.toString();
luvieere
  • 37,065
  • 18
  • 127
  • 179
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
  • Thanks! this is what I ending up doing :) – Juan Besa Mar 01 '09 at 05:50
  • 4
    For big arrays this is definitely not micro-optimizing. The automatic conversion to use StringBuilder is done separately for each string concatenation, which doesn't help in the case of a loop. It is OK if you concatenate a large number of elements in one expression. – starblue Mar 01 '09 at 10:43
  • 1
    Using the StringBuilder explicitly is a big deal if you are concatenating let's say 50 000 strings making ~ 1 MB result string - it can be a difference of 1 min compared to 1 s execution time. – Mr. Napik Sep 06 '13 at 08:32
36

Most Java projects often have apache-commons lang available. StringUtils.join() methods is very nice and has several flavors to meet almost every need.

public static java.lang.String join(java.util.Collection collection,
                                    char separator)


public static String join(Iterator iterator, String separator) {
    // handle null, zero and one elements before building a buffer 
    Object first = iterator.next();
    if (!iterator.hasNext()) {
        return ObjectUtils.toString(first);
    }
    // two or more elements 
    StringBuffer buf = 
        new StringBuffer(256); // Java default is 16, probably too small 
    if (first != null) {
        buf.append(first);
    }
    while (iterator.hasNext()) {
        if (separator != null) {
            buf.append(separator);
        }
        Object obj = iterator.next();
        if (obj != null) {
            buf.append(obj);
        }
    }
    return buf.toString();
}

Parameters:

collection - the Collection of values to join together, may be null

separator - the separator character to use

Returns: the joined String, null if null iterator input

Since: 2.3

Brian
  • 13,412
  • 10
  • 56
  • 82
  • 2
    This is very nice since the `join(...)` method has variants for both arrays and collections. – vikingsteve Nov 12 '13 at 12:49
  • I needed to create collections of strings with rarely populated elements, with random numbers. At the end I needed a string, not an array not array to string. This is my code : Collections.shuffle(L); StringBuilder sb = new StringBuilder(); L.forEach(e -> sb.append(e)); return sb.toString(); – dobrivoje Jan 19 '19 at 12:20
19

Android has a TextUtil class you can use:

String implode = TextUtils.join("\t", list);
user16217248
  • 3,119
  • 19
  • 19
  • 37
kehers
  • 4,076
  • 3
  • 30
  • 31
19

For this simple use case, you can simply join the strings with comma. If you use Java 8:

String csv = String.join("\t", yourArray);

otherwise commons-lang has a join() method:

String csv = org.apache.commons.lang3.StringUtils.join(yourArray, "\t");
Khader M A
  • 5,423
  • 3
  • 19
  • 19
15

In Java 8 it's simple. See example for list of integers:

String result = Arrays.asList(1,2,3).stream().map(Object::toString).reduce((t, u) -> t + "\t" + u).orElse("");

Or multiline version (which is simpler to read):

String result = Arrays.asList(1,2,3).stream()
    .map(Object::toString)
    .reduce((t, u) -> t + "\t" + u)
    .orElse("");

Update - a shorter version

String result = Arrays.asList(1,2,3).stream()
                .map(Object::toString)
                .collect(Collectors.joining("\t"));
amra
  • 16,125
  • 7
  • 50
  • 47
  • 3
    This might be only a line of code, but to me that doesn't look simple. For me traversing the List and parsing its elements into the String is simpler than this. – Bartzilla May 06 '15 at 01:14
  • 2
    This was my first impression too. But after I get used to it I find it awesome. For example you can add operations like `filter`. In the end it's much easier for me to read the code. – amra May 06 '15 at 10:10
  • 6
    In Java 8: String.join("\t", array) – Tomasz Aug 26 '15 at 09:21
  • The last comment works only if the content is a `String` as well. If its a list of `Integer`s you have a problem – LeO Jul 03 '19 at 10:53
  • All 3 of those requires API level 24 on android. – Asad35Waheed Apr 21 '20 at 11:38
13

An elegant way to deal with trailing separation characters is to use Class Separator

StringBuilder buf = new StringBuilder();
Separator sep = new Separator("\t");
for (String each: list) buf.append(sep).append(each);
String s = buf.toString();

The toString method of Class Separator returns the separater, except for the first call. Thus we print the list without trailing (or in this case) leading separators.

akuhn
  • 27,477
  • 2
  • 76
  • 91
6

In case you happen to be on Android and you are not using Jack yet (e.g. because it's still lacking support for Instant Run), and if you want more control over formatting of the resulting string (e.g. you would like to use the newline character as the divider of elements), and happen to use/want to use the StreamSupport library (for using streams on Java 7 or earlier versions of the compiler), you could use something like this (I put this method in my ListUtils class):

public static <T> String asString(List<T> list) {
    return StreamSupport.stream(list)
            .map(Object::toString)
            .collect(Collectors.joining("\n"));
}

And of course, make sure to implement toString() on your list objects' class.

Javad
  • 5,755
  • 4
  • 41
  • 51
  • 1
    Using `reduce` is extremely inefficient for String concatenation. You should do it the Java 8 way `return StreamSupport.stream(list).map(Object::toString).collect(joining("\n"))` which internally uses `StringJoiner`. There is no reason you couldn't do this with [streamsupport](https://sourceforge.net/projects/streamsupport/) also. – Stefan Zobel Sep 26 '16 at 18:31
  • Another thing is that your code would fail horribly (due to the `Optional#get`) if it gets passed an empty list. – Stefan Zobel Sep 26 '16 at 18:40
  • @StefanZobel Thanks for pointing out the efficiency and edge case issues. Modified the code. – Javad Sep 26 '16 at 18:46
6

It's an O(n) algorithm either way (unless you did some multi-threaded solution where you broke the list into multiple sublists, but I don't think that is what you are asking for).

Just use a StringBuilder as below:

StringBuilder sb = new StringBuilder();

for (Object obj : list) {
  sb.append(obj.toString());
  sb.append("\t");
}

String finalString = sb.toString();

The StringBuilder will be a lot faster than string concatenation because you won't be re-instantiating a String object on each concatenation.

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Mike C.
  • 1,035
  • 2
  • 8
  • 13
5

In one Line : From [12,0,1,78,12] to 12 0 1 78 12

String srt= list.toString().replaceAll("\\[|\\]|,","");
Pratyush Pranjal
  • 544
  • 6
  • 26
  • 2
    1) There's no reason to use code like this anymore (as of 4 years ago!). 2) This answer doesn't add anything to the Q&A. – Radiodef Jul 20 '18 at 17:00
  • This works perfectly. For comma separated string use: String srt= list.toString().replaceAll("\\[|\\]",""); – Asad35Waheed Apr 21 '20 at 11:36
4
List<String> stringList = getMyListOfStrings();
StringJoiner sj = new StringJoiner(" ");
stringList.stream().forEach(e -> sj.add(e));
String spaceSeparated = sj.toString()

You pass to the new StringJoiner the char sequence you want to be used as separator. If you want to do a CSV: new StringJoiner(", ");

fmsf
  • 36,317
  • 49
  • 147
  • 195
4

If you don't want the last \t after the last element, you have to use the index to check, but remember that this only "works" (i.e. is O(n)) when lists implements the RandomAccess.

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

StringBuilder sb = new StringBuilder(list.size() * apprAvg); // every apprAvg > 1 is better than none
for (int i = 0; i < list.size(); i++) {
    sb.append(list.get(i));
    if (i < list.size() - 1) {
        sb.append("\t");
    }
}
System.out.println(sb.toString());
3

If you're using Eclipse Collections, you can use the makeString() method.

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

Assert.assertEquals(
    "one\ttwo\tthree",
    ArrayListAdapter.adapt(list).makeString("\t"));

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertEquals(
    "one\ttwo\tthree",
    FastList.newListWith("one", "two", "three").makeString("\t"));

Note: I am a committer for Eclipse Collections.

Craig P. Motlin
  • 26,452
  • 17
  • 99
  • 126
3

The below code may help you,

List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = list.toString();
System.out.println("Step-1 : " + str);
str = str.replaceAll("[\\[\\]]", "");
System.out.println("Step-2 : " + str);

Output:

Step-1 : [1, 2, 3]
Step-2 : 1, 2, 3
Srinivasan.S
  • 3,065
  • 1
  • 24
  • 15
3

May not be the best way, but elegant way.

Arrays.deepToString(Arrays.asList("Test", "Test2")

import java.util.Arrays;

    public class Test {
        public static void main(String[] args) {
            System.out.println(Arrays.deepToString(Arrays.asList("Test", "Test2").toArray()));
        }
    }

Output

[Test, Test2]

Mohan Narayanaswamy
  • 2,149
  • 6
  • 33
  • 40
  • 1
    I think this is the best way if "best" means code readability. I haven't looked at the code, but it's probably just as efficient as the StringBuilder method (it probably uses a StringBuilder under the hood), though not as customizable in the output. – Mike Miller Nov 12 '14 at 22:28
3

Would the following be any good:

List<String> streamValues = new ArrayList<>();
Arrays.deepToString(streamValues.toArray()));   
Beezer
  • 1,084
  • 13
  • 18
2

For seperating using tabs instead of using println you can use print

ArrayList<String> mylist = new ArrayList<String>();

mylist.add("C Programming");
mylist.add("Java");
mylist.add("C++");
mylist.add("Perl");
mylist.add("Python");

for (String each : mylist)
{       
    System.out.print(each);
    System.out.print("\t");
}
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
chopss
  • 771
  • 9
  • 19
1

I see quite a few examples which depend on additional resources, but it seems like this would be the simplest solution: (which is what I used in my own project) which is basically just converting from an ArrayList to an Array and then to a List.

    List<Account> accounts = new ArrayList<>();

   public String accountList() 
   {
      Account[] listingArray = accounts.toArray(new Account[accounts.size()]);
      String listingString = Arrays.toString(listingArray);
      return listingString;
   }
Elliander
  • 503
  • 1
  • 9
  • 19
0

You can use a Regex for this. This is as concise as it gets

System.out.println(yourArrayList.toString().replaceAll("\\[|\\]|[,][ ]","\t"));
Vikrant Goel
  • 654
  • 6
  • 20
0

This is quite an old conversation by now and apache commons are now using a StringBuilder internally: http://commons.apache.org/lang/api/src-html/org/apache/commons/lang/StringUtils.html#line.3045

This will as we know improve performance, but if performance is critical then the method used might be somewhat inefficient. Whereas the interface is flexible and will allow for consistent behaviour across different Collection types it is somewhat inefficient for Lists, which is the type of Collection in the original question.

I base this in that we are incurring some overhead which we would avoid by simply iterating through the elements in a traditional for loop. Instead there are some additional things happening behind the scenes checking for concurrent modifications, method calls etc. The enhanced for loop will on the other hand result in the same overhead since the iterator is used on the Iterable object (the List).

Alex VI
  • 161
  • 3
-1

How about this function:

public static String toString(final Collection<?> collection) {
    final StringBuilder sb = new StringBuilder("{");
    boolean isFirst = true;
    for (final Object object : collection) {
        if (!isFirst)
            sb.append(',');
        else
            isFirst = false;
        sb.append(object);
    }
    sb.append('}');
    return sb.toString();
}

it works for any type of collection...

android developer
  • 114,585
  • 152
  • 739
  • 1,270