Output the contents of an ArrayList as a comma-separated String

Related searches

I am attempting to add a comma separator to the String representation of a Java ArrayList but nothing seems to work, I am obviously missing something simple.

Sadly old Java 6 (running in a JSP):

ArrayList zones= new ArrayList();
zones.add(pageContext.getAttribute("zone"));

for(int i=0; i<zones.size(); i++)
out.println(zones.get(i));

// output is   CellA116 CellA116 CellA116 Reception Reception CellA11

StringBuffer stringBuffer = new StringBuffer();
for(int i=0; i<zones.size(); i++)
{
stringBuffer.append(zones.get(i));
stringBuffer.append(",");
}

out.println(stringBuffer.toString());

// output is   CellA116,CellA116,CellA116,Reception,Reception,CellA11,  (commas)

  %>     

</tr>
</c:forEach>

syntax wont work here (outside of loop)
out.println(stringBuffer.substring(0, stringBuffer.length() - 1));

I need to remove the final comma (as I eventually want to use the array in chart.js), appreciate any thoughts.

Generally speaking, relying on a toString() method to do this is an easy way to inadvertently introduce bugs later on. If you change what concrete class is providing the collection (maybe to a Set instead of a List for example), your assumption that it starts and ends with square brackets might be untrue, and your output might change without you realising it.

I'd suggest that a more appropriate solution would be to iterate over the collection of Strings and add them to a StringBuilder.

So, it might look something like:

StringBuilder stringBuilder = new StringBuilder();
for(int i=0; i<strList.size(); i++)
{
    stringBuilder.append(strList.get(i));
    stringBuilder.append(",");
}

// Remove the last character from the StringBuilder to avoid a trailing comma.
String commaSeparatedList = stringBuilder.substring(0, stringBuilder.length() - 1);

out.println(commaSeparatedList);

How to convert a List<String> into a comma separated string without , i("Result", allIds);. To split all elements of String to arraylist with comma (","). String allIds =� There are several ways using which you can convert ArrayList to comma separated string as given below. 1) Convert ArrayList to comma separated string using StringBuilder. First, iterate through the ArrayList elements and append them one by one to the StringBuilder followed by a comma. In the end, convert StringBuilder to String object and remove the last extra comma from String. Example

You can utilize a StringBuilder and a classic for loop to output a csv line from List<String>.

Have a look at this:

public static void main(String args[]) {
    List<String> zones = new ArrayList<String>();
    zones.add("CellA116");
    zones.add("CellA116");
    zones.add("CellA116");
    zones.add("Reception");
    zones.add("Reception");
    zones.add("CellA11");

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < zones.size(); i++) {
        if (i < zones.size() - 1) {
            sb.append(zones.get(i)).append(";");
        } else {
            sb.append(zones.get(i));
        }
    }

    System.out.println(sb.toString());
}

The output will look like this:

CellA116;CellA116;CellA116;Reception;Reception;CellA11

If you want to have a method with a flexible separator char, then use something like this:

public static String toSeparatedString(List<String> values, char separator) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < values.size(); i++) {
        if (i < values.size() - 1) {
            sb.append(values.get(i)).append(separator);
        } else {
            sb.append(values.get(i));
        }
    }

    return sb.toString();
}

Java ArrayList to comma separated string example, 1) Convert ArrayList to comma separated string using StringBuilder. First, iterate through the ArrayList elements and append them one by one� To convert a comma separated String into an ArrayList. Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class. Example. Live Demo

I dont see the need for another for loop to replace the [] and , zones.toString().replaceAll("[\[\]\s]", "") suggested by Lino works well.

Java 8, Convert a List<String> in a String with all the values of the List System.out. println(citiesCommaSeparated); //Output: Milan,London,New York� To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method. Example

How to Convert a Comma Separated String to an ArrayList in Java , Suppose you have a comma-separated list of String e.g. "Samsung, Apple, Sony, 3) Create an ArrayList by copying contents from fixed length list - Use + listOfString.size()); Output : list of comma separated String : [Apple,� Convert a List to a Comma-Separated String in Java 8 This quick tutorial shows you how to use streams in Java to convert the contents of a list to a comma-separated string in Java 8. by

Convert a List of String to a comma separated String in Java , Form a comma separated String from the List of String using join() method by passing comma ' Print the String. list = new ArrayList<>(. You can use the split method to split comma separated values to an array of String. Iterate array, convert elements to Long using the parseLong method and add them to ArrayList one by one as given below. 1 2

The ArrayList class is part of the System.Collections namespace within .NET. By creating a new object of this type you can then store objects within an ArrayList. Below you can see that you need to explicitly create an ArrayList object using the New-Object cmdlet or by casting a standard array to an ArrayList object.

Comments
  • zones.toString().replaceAll("[\\[\\]\\s]", "")? Demo
  • If you can use Java 8, take a look at this: ideone.com/43GQlC
  • See this answer which also addresses the JSp context: Java: convert List<String> to a String
  • Possible duplicate of Java: convert List<String> to a String
  • I changed it to StringBuffer and that seems to work (commas included) but the substring attempt removes all the commas
  • StringBuffer should be fine too - see the first line of the StringBuilder docs for information about the difference.
  • Oh! You will need to have the .substring line outside the loop (i.e. after the loop has finished), if you have it inside the loop, that would remove the commas as you describe.
  • Thanks again, the loop is a jstl c:forEach loop so I have to fugure out how to do the substring outside of that loop
  • just some tips,in jsp forEach I guess there has a method to get the current count for the loop,if the count is not equal the size of the list,append comma. So the last comma will not show
  • Thanks but this if (i < values.size() - 1) causes an issue (either results in no output or strips all commas if already inserted)
  • @Ralph this is for a List<String> that has no commas inserted before but It will not strip out anything. How are you using it? The if statement just determines if the currently handled String is the last one and if it is, there will be no trailing separator character. That's the only purpose of it.