简体   繁体   English

如何转换列表<String>列表到 csv 字符串

[英]How to convert a List<String> list to csv string

I have a List of Strings .我有一个字符串List Is there a Java convenience method to convert this List to a CSV String ?是否有Java便捷方法将此List转换为CSV String So "test1, test2, test3" is the result of a conversion of a List 3 String elements which contains "test1" "test2" "test3"所以“test1,test2,test3”是包含“test1”“test2”“test3”的List 3 String元素的转换结果

I could write the method myself to convert the String but maybe this is implemented by the API already ?我可以自己编写方法来转换String但也许这已经由API实现了?

Apache Commons Lang contains a StringUtils.join() method for precisely this purpose. Apache Commons Lang包含一个StringUtils.join()方法正是为了这个目的。 Note that different flavours exist.请注意,存在不同的口味。

And as of March 2014, Java 8 now has a StringJoiner截至 2014 年 3 月,Java 8 现在有一个StringJoiner

If you are using Java 8如果您使用的是 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.有一个名为Joiner的 Guava 类可以轻松创建此类字符串。

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

There are a few useful methods in org.springframework.util.StringUtils . 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更多详情: 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,则可以使用以下内容。

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 Arrays.toString 将产生类似

[a], [b], [c]

if you list contains a, b, c如果您的列表包含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("[", ""我们可以使用逗号分隔的事实,在这里我们只需删除方括号并将它们替换为"以用于数据中逗号的情况。如果您不需要这个,您可以执行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.不,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 .编辑:这是CSV的拟议RFC

EDIT2: In case anyone is interested in an implementation please leave a comment, I have one wating on my harddisk at home. EDIT2:如果有人对实现感兴趣,请发表评论,我家里的硬盘上有一个。

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 {公共类 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: Android用户,您可以使用以下方法:

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

The second parameter will accept Object[] or an Iterable class.第二个参数将接受 Object[] 或 Iterable 类。

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

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

Looking to convert List to String Java ?想要将List转换为 String Java吗? Lets have a look at how to convert a Java Collections List of elements to a String in Java.让我们看看如何在 Java 中将元素的 Java 集合列表转换为字符串。

Basically List in Java is an ordered collection or a default sequence. Java 中的 List 基本上是一个有序集合或默认序列。

List accepts duplicate elements unlike Map doesnt accept duplicate values and also holds the object in key value pairs. List 接受重复元素,不像 Map 不接受重复值,并且还在键值对中保存对象。

We can print the contents of a List element in a readable form while debugging the code, which is helpful.我们可以在调试代码的同时,以可读的形式打印一个List元素的内容,这很有帮助。 From below Java program, lets see how to convert Java list to string array using toString method.从下面的 Java 程序中,让我们看看如何使用 toString 方法将 Java 列表转换为字符串数组。

We are passing integer argument (number) to create java string array using Arrays asList() method.我们正在传递整数参数(数字)以使用 Arrays asList() 方法创建 java 字符串数组。

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.从下面的 Java 程序中,让我们看看如何使用 toString 方法将 Java 列表转换为字符串数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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