Java list to string separated by comma

Convert a List to a Comma-Separated String in Java 8

Join the DZone community and get the full member experience.

Converting a List to a String with all the values of the List comma separated in Java 8 is really straightforward. Let’s have a look how to do that.

In Java 8

We can simply write String.join(..), pass a delimiter and an Iterable and the new StringJoiner will do the rest:

List cities = Arrays.asList("Milan", "London", "New York", "San Francisco"); String citiesCommaSeparated = String.join(",", cities); System.out.println(citiesCommaSeparated); //Output: Milan,London,New York,San Francisco

If we are working with stream we can write as follow and still have the same result:

String citiesCommaSeparated = cities.stream() .collect(Collectors.joining(",")); System.out.println(citiesCommaSeparated); //Output: Milan,London,New York,San Francisco

Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing «joining«.

In Java 7

For old times’ sake, let’s have a look at the Java 7 implementation:

private static final String SEPARATOR = ","; public static void main(String[] args) < Listcities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); StringBuilder csvBuilder = new StringBuilder(); for(String city : cities) < csvBuilder.append(city); csvBuilder.append(SEPARATOR); >String csv = csvBuilder.toString(); System.out.println(csv); //OUTPUT: Milan,London,New York,San Francisco, //Remove last comma csv = csv.substring(0, csv.length() - SEPARATOR.length()); System.out.println(csv); //OUTPUT: Milan,London,New York,San Francisco >

As you can see it’s much more verbose and easier to make mistakes like forgetting to remove the last comma. You can implement this in several ways—for example by moving the logic that removes the last comma to inside the for-loop—but no implementation will be so explicative and easy to understand as the declarative solution expressed in Java 8.

Focus should be on what you want to do—joining a List of String—not on how.

Java 8: Manipulate String Before Joining

If you are using Stream, it’s really straightforward manipulate your String as you prefer by using map() or cutting some String out by using filter(). I’ll cover those topics in future articles. Meanwhile, this a straightforward example on how to transform the whole String to upper-case before joining.

Java 8: From List to Upper-Case String Comma Separated

String citiesCommaSeparated = cities.stream() .map(String::toUpperCase) .collect(Collectors.joining(",")); //Output: MILAN,LONDON,NEW YORK,SAN FRANCISCO

If you want to find out more about stream, I strongly suggest this cool video from Venkat Subramaniam.

Читайте также:  Css display block center image

Let’s Play

The best way to learn is playing! Copy this class with all the implementations discussed and play with that. There is already a small test for each of them.

package net.reversecoding.examples; import static java.util.stream.Collectors.joining; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.Test; public class CsvUtil < private static final String SEPARATOR = ","; public static String toCsv(List < String >listToConvert) < return String.join(SEPARATOR, listToConvert); >@Test public void toCsv_csvFromListOfString() < List < String >cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "Milan,London,New York,San Francisco"; assertEquals(expected, toCsv(cities)); > public static String toCsvStream(List < String >listToConvert) < return listToConvert.stream() .collect(joining(SEPARATOR)); >@Test public void toCsvStream_csvFromListOfString() < List < String >cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "Milan,London,New York,San Francisco"; assertEquals(expected, toCsv(cities)); > public static String toCsvJava7(List < String >listToConvert) < StringBuilder csvBuilder = new StringBuilder(); for (String s: listToConvert) < csvBuilder.append(s); csvBuilder.append(SEPARATOR); >String csv = csvBuilder.toString(); //Remove last separator if (csv.endsWith(SEPARATOR)) < csv = csv.substring(0, csv.length() - SEPARATOR.length()); >return csv; > @Test public void toCsvJava7_csvFromListOfString() < List < String >cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "Milan,London,New York,San Francisco"; assertEquals(expected, toCsvJava7(cities)); > public static String toUpperCaseCsv(List < String >listToConvert) < return listToConvert.stream() .map(String::toUpperCase) .collect(joining(SEPARATOR)); >@Test public void toUpperCaseCsv_upperCaseCsvFromListOfString() < List < String >cities = Arrays.asList( "Milan", "London", "New York", "San Francisco"); String expected = "MILAN,LONDON,NEW YORK,SAN FRANCISCO"; assertEquals(expected, toUpperCaseCsv(cities)); > >

If you enjoyed this article and want to learn more about Java Streams, check out this collection of tutorials and articles on all things Java Streams.

Published at DZone with permission of Mario Pio Gioiosa , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Best way to convert list to comma separated string in java [duplicate]

If your app involves Spring then it has a utility method collectionToCommaDelimitedString. I wouldn’t pull the library in just for that but if you’re using it already.

3 Answers 3

From Apache Commons library:

import org.apache.commons.lang3.StringUtils 

Another similar question and answer here

@HemantG For the Android users: TextUtils.join() expects the parameters in a different order than StringUtils . It’s TextUtils.join(delimiter, iterable) . For example, the code above would be TextUtils.join(‘,’, slist); Source

Читайте также:  Regular expression check in java

If you’re using Java 8 and you don’t want to use the streams api then you can simply do String.join(«,», slist);

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set abc = new HashSet(); abc.add("A"); abc.add("B"); abc.add("C"); String separator = ", "; int total = abc.size() * separator.length(); for (String s : abc) < total += s.length(); >StringBuilder sb = new StringBuilder(total); for (String s : abc) < sb.append(separator).append(s); >String result = sb.substring(separator.length()); // remove leading separator 

You have to run through the String twice. So it is effectively an N^2 algorithm. Really long strings would perform terribly, and depending on your application open up a DoS attack vector.

@Kay I do very much. An algorithm whose run time increases logarithmically as a function of the number of objects it operates on. Why did I miscalculate somehow? Did I misread your code? in it you go through the same string 2 times, the first to count the total the second to append the string and the separator. Imagine instead of a set of three you had a set of 3 million? Can you imagine how long the run-time of that solution is?

Well, I stand corrected. Your right. In your example you don’t loop for each element in the string. You literally just run against the length twice, which would be constant. Way to keep me honest. Keep up the good work.

Источник

How to convert a List into a comma separated string without iterating List explicitly [duplicate]

Define «iterating it fully», because neither god, cthulu, nor the flying spaghetti monster could get the items out of the list without iterating over all of it in some manner.

13 Answers 13

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

TextUtils has so many hidden gems — Google should do a better job at promoting them. They also have other util classes that are awesome and not well known.

String csv = String.join(",", ids); 

With Java 7-, there is a dirty way (note: it works only if you don’t insert strings which contain «, » in your list) — obviously, List#toString will perform a loop to create idList but it does not appear in your code:

List ids = new ArrayList(); ids.add("1"); ids.add("2"); ids.add("3"); ids.add("4"); String idList = ids.toString(); String csv = idList.substring(1, idList.length() - 1).replace(", ", ","); 
import com.google.common.base.Joiner; Joiner.on(",").join(ids); 

or you can use StringUtils:

 public static String join(Object[] array, char separator) public static String join(Iterable iterator, char separator) 

Joins the elements of the provided array/iterable into a single String containing the provided list of elements.

+1 — Joiner works with an iterable or object array, and can do things like skipping nulls in the input.

Читайте также:  Windows internet explorer javascript

If you want to convert list into the CSV format .

List ids = new ArrayList(); ids.add("1"); ids.add("2"); ids.add("3"); ids.add("4"); // CSV format String csv = ids.toString().replace("[", "").replace("]", "") .replace(", ", ","); // CSV format surrounded by single quote // Useful for SQL IN QUERY String csvWithQuote = ids.toString().replace("[", "'").replace("]", "'") .replace(", ", "','"); 

And hope that java won’t change the to string of list. It’s a risky way wouldn’t use this in a productive system.

Don’t forget to import StringUtils : import org.apache.commons.lang3.StringUtils commons-lang3 is a great library for String related methods.

String joinedString = ids.toString() 

will give you a comma delimited list. See docs for details.

You will need to do some post-processing to remove the square brackets, but nothing too tricky.

One Liner (pure Java)

list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", ""); 

Join / concat & Split functions on ArrayList:

To Join /concat all elements of arraylist with comma,«) to String.

List ids = new ArrayList(); ids.add("1"); ids.add("2"); ids.add("3"); ids.add("4"); String allIds = TextUtils.join(",", ids); Log.i("Result", allIds); 

To split all elements of String to arraylist with comma,«).

String allIds = "1,2,3,4"; String[] allIdsArray = TextUtils.split(allIds, ","); ArrayList idsList = new ArrayList(Arrays.asList(allIdsArray)); for(String element : idsList)

I am having ArrayList of String, which I need to convert to comma separated list, without space. The ArrayList toString() method adds square brackets, comma and space. I tried the Regular Expression method as under.

List myProductList = new ArrayList(); myProductList.add("sanjay"); myProductList.add("sameer"); myProductList.add("anand"); Log.d("TEST1", myProductList.toString()); // "[sanjay, sameer, anand]" String patternString = myProductList.toString().replaceAll("[\\s\\[\\]]", ""); Log.d("TEST", patternString); // "sanjay,sameer,anand" 

Please comment for more better efficient logic. ( The code is for Android / Java )

Источник

Оцените статью