简体   繁体   中英

How to convert a List<String> list to csv string

I have a List of Strings . Is there a Java convenience method to convert this List to a CSV String ? So "test1, test2, test3" is the result of a conversion of a List 3 String elements which contains "test1" "test2" "test3"

I could write the method myself to convert the String but maybe this is implemented by the API already ?

Apache Commons Lang contains a StringUtils.join() method for precisely this purpose. Note that different flavours exist.

And as of March 2014, Java 8 now has a StringJoiner

If you are using Java 8

List<String> objects= Arrays.asList("Test1","Test2","Test3");
String objectsCommaSeparated = String.join(",", objects);
System.out.println(objectsCommaSeparated);

With Streams

String objectsCommaSeparated = objects.stream().collect(Collectors.joining(","));
System.out.println(objectsCommaSeparated);

There is a Guava class called Joiner that can easily create these kind of Strings.

Do Joiner.on(",").join(yourStrings)

There are a few useful methods in org.springframework.util.StringUtils .

Example:

String text = StringUtils.arrayToCommaDelimitedString(new Object[]{"test1", "test2", "test3"});

For more details: http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/util/StringUtils.html

Wrote this simple method;

String listToCsv(List<String> listOfStrings, char separator) {
    StringBuilder sb = new StringBuilder();

    // all but last
    for(int i = 0; i < listOfStrings.size() - 1 ; i++) {
        sb.append(listOfStrings.get(i));
        sb.append(separator);
    }

    // last string, no separator
    if(listOfStrings.size() > 0){
        sb.append(listOfStrings.get(listOfStrings.size()-1));
    }

    return sb.toString();
}

I think you could use the following if you wanted to just use core java.

java.util.Arrays.toString(list.toArray(new String[list.size()]).replace("[", "\"").replace("]", "\"");

Warning: I have not checked all cases of this. ;)

The Arrays.toString will produce something like

[a], [b], [c]

if you list contains a, b, c

We can use the fact that it is comma separated to our advantage here and just remove the square brackets and replace them with " for the case where commas are within the data. If you dont need this you can just do replace("[", ""

public class StringUtil {

    public String toCsv(final List<?> list) {
        return toString(list, ',');
    }

    public String toString(final List<?> list, char delimiter) {
        final StringBuilder b = new StringBuilder();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                b.append(list.get(i).toString());
                if (i != list.size() - 1) {
                    b.append(delimiter);
                }
            }
        }
        return b.toString();
    }
}

No, there is no convenience method available in the JDK. You could create your own, but for the general case this is not as trivial as it seems (for example when a field contains a separator, newline character, or a textdelimiter):

  • field conatins newline: field has to be quoted
  • field contains textdelimiter: delimiter is doubled
  • field contains separator: field has to be quoted

Example:

String[] fields = { "\n", ""he said \"hello\"", "," }

should give you this:

"
","he said ""hello""",","

EDIT: Here's a proposed RFC for CSV .

EDIT2: In case anyone is interested in an implementation please leave a comment, I have one wating on my harddisk at home.

This is what Im doing

  @Test
    public void testString(){
        List<String> listOfWords = Arrays.asList("Some","Other","lalala");

        final String fields = listOfWords.stream().reduce((t, u) -> t + "," + u).get();
        System.out.println("Look "+fields);
    }

This code handles data containing quotes, commas and other troublesome characters:

public class ToCsv {

 private static final String QUOTE = "\\""; private static final Pattern NON_WORD = Pattern.compile(".*\\\\W.*"); public final static String toCsv(final List<Object> list) { final StringBuilder sb = new StringBuilder(); String sep = ""; for (final Object object : list) { String s = object.toString(); final Matcher m = NON_WORD.matcher(s); if (m.matches()) { if (s.contains(QUOTE)) { s = s.replaceAll(QUOTE, "\\"\\""); } sb.append(sep).append(QUOTE).append(s).append(QUOTE); } else { sb.append(sep).append(s); } sep = ","; } return sb.toString(); } }

Use this code

 public static String listToString(List list) {

        int len = list.size();
        int last = len - 1;
        StringBuffer sb = new StringBuffer(2 * (len + 1));

        sb.append('{');

        for (int i = 0; i < len; i++) {
            sb.append(list.get(i));

            if (i != last) {
                sb.append(',');
            }
        }

        sb.append('}');

        return sb.toString();
    }

Android users, you can use the following:

TextUtils.join(",", getCollectionOfStrings());

The second parameter will accept Object[] or an Iterable class.

我知道现在已经很晚了,但我没有看到有人用Java 8 方式回答过:

String csvString = String.join(",", myStringList);

Looking to convert List to String Java ? Lets have a look at how to convert a Java Collections List of elements to a String in Java.

Basically List in Java is an ordered collection or a default sequence.

List accepts duplicate elements unlike Map doesnt accept duplicate values and also holds the object in key value pairs.

We can print the contents of a List element in a readable form while debugging the code, which is helpful. From below Java program, lets see how to convert Java list to string array using toString method.

We are passing integer argument (number) to create java string array using Arrays asList() method.

In other words, we are passing list of integers as array to list. From below Java program, lets see how to convert Java list to string array using toString method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM