如何将列表转换为逗号分隔字符串,而不显式地重复列表[复制]

时间:2022-09-02 00:21:02

This question already has an answer here:

这个问题已经有了答案:

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

Now i want an output from this list as 1,2,3,4 without explicitly iterating over it.

现在我想要这个列表中的输出为1,2,3,4,而不需要显式地迭代它。

13 个解决方案

#1


362  

On Android use:

在Android上使用:

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

#2


110  

With Java 8:

与Java 8:

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:

对于Java 7-,有一种肮脏的方法(注意:只有在不插入包含“,”的字符串时,它才能工作)-显然,列表#toString将执行一个循环来创建idList,但它不会出现在您的代码中:

List<String> ids = new ArrayList<String>();
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(", ", ",");

#3


99  

import com.google.common.base.Joiner;

Joiner.on(",").join(ids);

or you can use StringUtils:

或者你可以用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.

将提供的数组/iterable的元素连接到包含提供的元素列表的单个字符串。

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

#4


60  

If you want to convert list into the CSV format .........

如果你想要将清单转换成CSV格式,请提供给我

List<String> ids = new ArrayList<String>();
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(", ", "','");

#5


49  

The quickest way is

最快的方法是

StringUtils.join(ids, ",");

#6


18  

The following:

以下几点:

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.

您将需要做一些后处理,以删除方括号,但不要太棘手。

#7


12  

Join / concat & Split functions on ArrayList:

ArrayList上的Join / concat和Split函数:

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

将arraylist的所有元素以逗号(",")连接到字符串。

List<String> ids = new ArrayList<String>();
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 (",").

用逗号(“,”)将字符串的所有元素分割为arraylist。

String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
    Log.i("Result", element);
}

Done

完成

#8


11  

One Liner (pure Java)

一个衬套(纯Java)

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

#9


6  

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.

我有一个字符串数组,我需要把它转换成逗号分隔的列表,没有空格。ArrayList toString()方法添加方括号、逗号和空格。我尝试了如下的正则表达式方法。

List<String> myProductList = new ArrayList<String>();
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 )

请评论以获得更有效的逻辑。(代码为Android / Java)

Thankx.

Thankx。

#10


4  

Java 8 solution if it's not a collection of strings:

如果不是字符串集合,Java 8解决方案:

{Any collection}.stream()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString()

#11


3  

You can use below code if object has attibutes under it.

如果对象下面有注释,可以使用下面的代码。

String getCommonSeperatedString(List<ActionObject> actionObjects) {
    StringBuffer sb = new StringBuffer();
    for (ActionObject actionObject : actionObjects){
        sb.append(actionObject.Id).append(",");
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    return sb.toString();
}

#12


3  

If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.

如果您正在使用Eclipse集合(以前是GS集合),您可以使用makeString()方法。

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

Assert.assertEquals("1,2,3,4", ListAdapter.adapt(ids).makeString(","));

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

如果可以将ArrayList转换为FastList,则可以去掉适配器。

Assert.assertEquals("1,2,3,4", FastList.newListWith(1, 2, 3, 4).makeString(","));

Note: I am a committer for Eclipse collections.

注意:我是Eclipse集合的提交者。

#13


0  

Here is code given below to convert a List into a comma separated string without iterating List explicitly for that you have to make a list and add item in it than convert it into a comma separated string

下面给出的代码用于将列表转换为逗号分隔的字符串,而无需显式地迭代列表,因为您必须创建一个列表并在其中添加项,而不是将其转换为逗号分隔的字符串

Output of this code will be: Veeru,Nikhil,Ashish,Paritosh

此代码的输出将是:Veeru、Nikhil、Ashish、Paritosh

instead of output of list [Veeru,Nikhil,Ashish,Paritosh]

而不是输出列表[Veeru,Nikhil,Ashish,Paritosh]

String List_name;
List<String> myNameList = new ArrayList<String>();
myNameList.add("Veeru");
myNameList.add("Nikhil");
myNameList.add("Ashish");
myNameList.add("Paritosh");

List_name = myNameList.toString().replace("[", "")
                    .replace("]", "").replace(", ", ",");

#1


362  

On Android use:

在Android上使用:

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

#2


110  

With Java 8:

与Java 8:

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:

对于Java 7-,有一种肮脏的方法(注意:只有在不插入包含“,”的字符串时,它才能工作)-显然,列表#toString将执行一个循环来创建idList,但它不会出现在您的代码中:

List<String> ids = new ArrayList<String>();
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(", ", ",");

#3


99  

import com.google.common.base.Joiner;

Joiner.on(",").join(ids);

or you can use StringUtils:

或者你可以用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.

将提供的数组/iterable的元素连接到包含提供的元素列表的单个字符串。

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

#4


60  

If you want to convert list into the CSV format .........

如果你想要将清单转换成CSV格式,请提供给我

List<String> ids = new ArrayList<String>();
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(", ", "','");

#5


49  

The quickest way is

最快的方法是

StringUtils.join(ids, ",");

#6


18  

The following:

以下几点:

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.

您将需要做一些后处理,以删除方括号,但不要太棘手。

#7


12  

Join / concat & Split functions on ArrayList:

ArrayList上的Join / concat和Split函数:

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

将arraylist的所有元素以逗号(",")连接到字符串。

List<String> ids = new ArrayList<String>();
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 (",").

用逗号(“,”)将字符串的所有元素分割为arraylist。

String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
    Log.i("Result", element);
}

Done

完成

#8


11  

One Liner (pure Java)

一个衬套(纯Java)

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

#9


6  

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.

我有一个字符串数组,我需要把它转换成逗号分隔的列表,没有空格。ArrayList toString()方法添加方括号、逗号和空格。我尝试了如下的正则表达式方法。

List<String> myProductList = new ArrayList<String>();
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 )

请评论以获得更有效的逻辑。(代码为Android / Java)

Thankx.

Thankx。

#10


4  

Java 8 solution if it's not a collection of strings:

如果不是字符串集合,Java 8解决方案:

{Any collection}.stream()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString()

#11


3  

You can use below code if object has attibutes under it.

如果对象下面有注释,可以使用下面的代码。

String getCommonSeperatedString(List<ActionObject> actionObjects) {
    StringBuffer sb = new StringBuffer();
    for (ActionObject actionObject : actionObjects){
        sb.append(actionObject.Id).append(",");
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    return sb.toString();
}

#12


3  

If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.

如果您正在使用Eclipse集合(以前是GS集合),您可以使用makeString()方法。

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

Assert.assertEquals("1,2,3,4", ListAdapter.adapt(ids).makeString(","));

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

如果可以将ArrayList转换为FastList,则可以去掉适配器。

Assert.assertEquals("1,2,3,4", FastList.newListWith(1, 2, 3, 4).makeString(","));

Note: I am a committer for Eclipse collections.

注意:我是Eclipse集合的提交者。

#13


0  

Here is code given below to convert a List into a comma separated string without iterating List explicitly for that you have to make a list and add item in it than convert it into a comma separated string

下面给出的代码用于将列表转换为逗号分隔的字符串,而无需显式地迭代列表,因为您必须创建一个列表并在其中添加项,而不是将其转换为逗号分隔的字符串

Output of this code will be: Veeru,Nikhil,Ashish,Paritosh

此代码的输出将是:Veeru、Nikhil、Ashish、Paritosh

instead of output of list [Veeru,Nikhil,Ashish,Paritosh]

而不是输出列表[Veeru,Nikhil,Ashish,Paritosh]

String List_name;
List<String> myNameList = new ArrayList<String>();
myNameList.add("Veeru");
myNameList.add("Nikhil");
myNameList.add("Ashish");
myNameList.add("Paritosh");

List_name = myNameList.toString().replace("[", "")
                    .replace("]", "").replace(", ", ",");