4

Hi I'm writing code to print all elements from an ArrayList separated by comma, the folllowing is the method I wrote. It works. But i'm wondering if it can be simplified? And is there a more elegant way to print all elements from an ArrayList separated by some delimiter? (e.g. a method that prints an ArrayList of Strings get "Tom, Sherlock, Jack")

Thanks everyone!

public String printMyArrayList() {
    if(mylist.size() == 0)return "";
    else if(mylist.size() == 1)return mylist.get(0).toString();
    else {
        String returnStr = "";
        for (int i = 0; i < mylist.size() ; i++) {
            if(i == 0)returnStr = mylist.get(i).toString();
            else {
                returnStr = returnStr + ", " + mylist.get(i).toString();
            }
        }
        return returnStr;
    }
}
Jerry Tang
  • 129
  • 1
  • 1
  • 4
  • possible duplicate of [A quick and easy way to join array elements with a separator (the opposite of split) in Java](http://stackoverflow.com/questions/1978933/a-quick-and-easy-way-to-join-array-elements-with-a-separator-the-opposite-of-sp), and [What's the best way to build a string of delimited items in Java?](http://stackoverflow.com/questions/63150/whats-the-best-way-to-build-a-string-of-delimited-items-in-java) – Jongware Apr 29 '15 at 10:07
  • Remember to check if `mylist` is `null` before checking the size, it may produce a `NullPointerException` otherwise – Ian2thedv Apr 29 '15 at 10:19
  • 1
    @Ian2thedv and that is probably a good thing, because a list should never be null in the first place. Checking for null would hide a bug. – JB Nizet Apr 29 '15 at 10:20
  • @KarolKrol: OP himself alternates between calling it *printing* and *joining*. The suggested (already working!) code is *called* `print..` but it doesn't really do that. Also: printing *could* be programmed in a different way than first joining and then printing, but there is no reason to. – Jongware Apr 29 '15 at 12:48

7 Answers7

9

Using Collectors.joining from Java 8:

return list.stream()
           .map(Object::toString)
           .collect(Collectors.joining(", "));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4

Another Java 8 solution using String.join:

List<String> l = Arrays.asList(new String[] {"foo", "bar", "baz"});

String joined = String.join(", ", l);

System.out.println(joined);

Output:

foo, bar, baz
  • OP is using `item.toString()` which suggest that this is not List of Strings or other CharSequence so `String.join` can't be used here. – Pshemo Apr 29 '15 at 10:14
  • @Pshemo Sure, but that is not the point of the question. The joining is the intersting part, not converting objects to Strings. –  Apr 29 '15 at 10:17
  • I am not saying that tit is bad solution, but since OP seems to ask how to elegantly print list of *any elements* (not only `CharSequence`) I would say that mentioning that this solution will work only for types which can be used as `List` `CharSequence[]` is quite important. – Pshemo Apr 29 '15 at 10:24
1

A one-liner.

System.out.println(myArrayList.toString().replaceAll("\\[\\]", ""));

I.e. get the default String representation (which is [1, 2, 3]) and remove the braces.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

Try this:

String delimiter = "";
StringBuilder sb = new StringBuilder();
for (Item x : list) {
    sb.append(delimiter).append(x);
    delimiter = ",";
}

You can also use the Joiner class

Joiner.on(",").join(lst)
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

If you're working with android try this:

android.text.TextUtils.join(", ", listOfObjects);

else there's a util in spring framework.

org.springframework.util.StringUtils.arrayToCommaDelimitedString(listOfObjects);
malmling
  • 2,398
  • 4
  • 19
  • 33
-1

I don't know what you mean by "simple and elegant", but I'll go with it.

EDIT: String.join is probably the best way

DOUBLE EDIT: Don't use this, as pointed out in the comments below.

public String printMyArrayList(ArrayList<String> list)
{
   String result = "";
   for(String s : list)
   {
      result += s + ", ";
   }
   return result.substring(0, result.length()-2);
}
LuigiPower
  • 1,113
  • 10
  • 20
  • 1
    That is quite inefficient: it produces a lot of temporary String instances. – JB Nizet Apr 29 '15 at 10:11
  • 1
    I'll admit I should have put more thought on this one. I append the delimiter on each loop so I had to remove that last part. I'll leave this answer here as a "How not to do this" kind of thing. – LuigiPower Apr 29 '15 at 10:15
-1

Use List#toString method. It will enclose with []. If you don't want to include [] than you can substring it.

   String listStr= list.toString();
   String withoutSym= listStr.substring(1, listStr.length()-1);
Masudul
  • 21,823
  • 5
  • 43
  • 58