Java8-如何将List转变为逗号分隔的字符串

翻译 2017年06月04日 19:30:24

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.

在Java 8中将集合List转变为用逗号分隔的String是非常简单的,下面让我看看如何做到

In Java 8

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

我们使用String.join()函数,给函数传递一个分隔符合一个迭代器,一个StringJoiner对象会帮助我们完成所有的事情

List<String> 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:

由于老的缘故,让我们看看在java 7中如何实现这个功能

private static final String SEPARATOR = ",";
public static void main(String[] args) {
  List<String> cities = 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.

正如你所看到的,这种方式更加啰嗦并且更加容易犯诸如忘记去除最后一个逗号之类的错误。你能够采用几种方式来完成这一功能-例如你可以将删除最后一个逗号的操作逻辑放到for循环中,但是没有一种实现方式向java 8中如此可解释性并且容易理解

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

注意力应该放到你想做什么-连接List结合,而不是怎样做

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: 在连接之前操作字符串

如果你使用流,使用map函数或者用于删掉一些字符串的filter函数能够更加直观的操作字符串。我在将来的文章中会覆盖这些主题。同时,这也是一个直观展示如何将整个字符串在连接之前转为大写的例子。

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

将List集合转为大写的用逗号分隔的String

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.

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));
}
}

java List转换为字符串并加入分隔符的一些方法总结

方法一: public String listToString(List list, char separator) { StringBuilder sb = new StringBuilde...
  • fanyuna
  • fanyuna
  • 2014年07月08日 19:59
  • 98355

如何相互转换逗号分隔的字符串和List (Java程序员日记 2015/03/06)

如果程序员想实现某种功能,有两条路可以走。一条就是自己实现,一条就是调用别人的实现,别人的实现就是所谓的API。而且大多数情况下,好多“别人”都实现了这个功能。程序员有不得不在这其中选择。大部分情况下...
  • yywusuoweile
  • yywusuoweile
  • 2015年12月15日 14:47
  • 28533

String数组转List,List转String数组

List list = new ArrayList(); list.add("a1"); list.add("a2"); String[] toBeStored =...
  • aaronuu
  • aaronuu
  • 2011年12月09日 09:17
  • 145602

String 和List<String> 的互相转换

有时候为了方便数据的存储和传递等,需要把List 转换成String ,然后又需要还原,所以把方法记在博客里,方便自己查找。 List 转换成 String : 迭代List的每个子项,将他们用“,”...
  • shareye1992
  • shareye1992
  • 2015年11月25日 14:30
  • 25566

把List<String>转化为以","隔开的字符串的方法

1. [代码][Java]代码     1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ...
  • sx_ygl
  • sx_ygl
  • 2016年08月08日 15:13
  • 2649

JAVA中List转换String,String转换List,Map转换String,String转换Map之间的转换类

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; ...
  • qq7342272
  • qq7342272
  • 2011年09月28日 16:59
  • 96374

从string[]转list<string> 从list<string>转string[]

从string[]转list string[] str={"1","2"}; list list=new list(str); 从list转string[] list list=new l...
  • hefeng_aspnet
  • hefeng_aspnet
  • 2012年12月04日 14:49
  • 1616

使用StringUtils工具类将集合数组等转换为字符串

首先导入xwork-core.jar的StringUtils类: import org.apache.commons.lang.xwork.StringUtils; 第一:list转换...
  • aboboo5200
  • aboboo5200
  • 2017年04月21日 12:15
  • 3181

用string.Join与List<T>或者与string数组转换为字符串

直接贴代码了,有注释,代码已测试。 将List 转换为 字符串 List listStr = new List(); listStr.Add("a"); ...
  • Andrew_wx
  • Andrew_wx
  • 2011年07月11日 13:28
  • 23369

将List集合转化为用符号隔开的String字符串

org.apache.commons.lang3.StringUtils.join(list, ",")
  • qq_34698126
  • qq_34698126
  • 2017年06月20日 14:43
  • 1462
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Java8-如何将List转变为逗号分隔的字符串
举报原因:
原因补充:

(最多只允许输入30个字)