`
weitao1026
  • 浏览: 992022 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

 
阅读更多

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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".
  • 1
  • 2
  • 3
  • 4
  • 5

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
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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.
  • 1
  • 2
  • 3
  • 4
  • 5

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

 

分享到:
评论

相关推荐

    SQLServer逗号分隔的字符串转换成表

    SQLServer逗号分隔的字符串转换成表

    c# 字符串操作类

    /// 4、GetArrayStr(List list) 得到数组列表以逗号分隔的字符串 /// 5、GetArrayValueStr(Dictionary, int&gt; list)得到数组列表以逗号分隔的字符串 /// 6、DelLastComma(string str)删除最后结尾的一个逗号 /// ...

    list-to-array:简单的javascript库,用于转换[逗号|| 空格]分隔字符串到数组

    简单的javascript库,用于转换[逗号|| 空格]分隔字符串到数组。 修剪值,以便您可以使用对人友好的列表,例如'one, two, three' =&gt; ['one','two','three'] 如果提供了in array,则将其简单地返回。 如果提供错误或...

    C# Split函数根据特定分隔符分割字符串的操作

    在C#程序开发过程中,很多时候可能需要将字符串根据特定的分割字符分割成字符或者List集合,例如根据逗号将字符串分割为数组,...//根据逗号分隔字符串str 分隔完成之后的得到的数组strArr,取值为 strArr[0]=”A”

    Json对象与Json字符串互转(4种转换方式)

    //jQuery.parseJSON(jsonstr),可以将json字符串转换成json对象 2&gt;浏览器支持的转换方式(Firefox,chrome,opera,safari,ie9,ie8)等浏览器: 代码如下: JSON.parse(jsonstr); //可以将json字符串转换成json...

    Mysql字符串处理函数详细介绍、总结

    一、简明总结ASCII(char...x,y,instr) 将字符串str从第x位置开始,y个字符长的子串替换为字符串instr,返回结果FIND_IN_SET(str,list) 分析逗号分隔的list列表,如果发现str,返回str在list中的位置LCASE(str)或LOWER

    测量程序编制 - python 20数据类型:List(列表)-概述.pptx

    list1 = [‘hello', ‘Python', 2020, 2021]list2 = [1, 2, 3, 4, 5 ]list3 = ["a", "b", "c", "d"]list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']List(列表)访问列表中的值与字符串一样与Python...

    Java面试宝典-经典

    3、编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉...

    php中利用explode函数分割字符串到数组

    //按逗号分离字符串 $hello = explode(‘,’,$source); for($index=0;$index”; } ?&gt; //split函数进行字符分割 // 分隔符可以是斜线,点,或横线 复制代码 代码如下: &lt;?php $date = “04/30/1973”; list

    总结的5个C#字符串操作方法分享

    主要介绍了总结的5个C#字符串操作方法分享,本文讲解了把字符串按照分隔符转换成 List、把字符串转 按照, 分割 换为数据、得到数组列表以逗号分隔的字符串、得到字符串长度等方法,需要的朋友可以参考下

    pg-anonymizer:使用NodeJS CLI转储匿名的PostgreSQL数据库

    pg匿名器 匿名导出您的PostgreSQL数据库。 多亏了faker替换了所有敏感数据。 输出到一个可以使用psql轻松导入的文件。...使用--list选项和以逗号分隔的列名列表: npx pg-anonymizer postgres://localhost/mydb

    2-3-python编程基础知识-基本数据类型PPT课件.pptx

    以字母r或R引导的表示原始字符串 字节串 bytes b'hello world' 以字母b引导,可以使用单引号、双引号、三引号作为定界符 列表 list [1, 2, 3],['a', 'b', ['c', 2]] 所有元素放在一对方括号中,元素之间使用逗号...

    java面试宝典

    55、编码转换:怎样将GB2312 编码的字符串转换为ISO-8859-1 编码的字符串? 14 56、写一个函数,要求输入一个字符串和一个字符长度,对该字符串进行分隔。 14 59、Java 编程,打印昨天的当前时刻。 15 60、java 和...

    python入门到高级全栈工程师培训 第3期 附课件代码

    08 Python 字符串的魔法 第11章 01 Python 字符串的魔法 02 Python range的用法以及练习 03 Python 课上练习解释 04 Python 基础知识练习题试题 第12章 01 今日内容介绍以及基础测试题答案讲解 02 Python 列表的...

    一个java正则表达式工具类源代码.zip(内含Regexp.java文件)

    22. 匹配由26个英文字母的大写组成的字符串 23 匹配由26个英文字母的小写组成的字符串 24 匹配由数字和26个英文字母组成的字符串; 25 匹配由数字、26个英文字母或者下划线组成的字符串; java源码: /* * Created ...

    Oracle P/L SQL实现发送Email、浏览网页等网络操作功能

    --字符串根据特定分隔符分来 --Select UTL_INet.f_SplitString( 'A,B,C', xx, ',' ) From dual; Function f_SplitString( as_SourStr in out Clob, --输入字符串A,B,C as_Separator in VarChar2 ...

    入门学习Linux常用必会60个命令实例详解doc/txt

    文件为doc版,可自行转成txt,在手机上看挺好的。 本资源来自网络,如有纰漏还请告知,如觉得还不错,请留言告知后来人,谢谢!!!!! 入门学习Linux常用必会60个命令实例详解 Linux必学的60个命令 Linux提供...

    java收银系统源码-convenience-store:便利店

    upc(字符串)、名称(字符串)、批发价格(编号或子类)、零售价格(编号或子类)和数量(编号或子类)。 将标准的 getter 和 setter getName()、setName() 等添加到 Product 类。 IInventory 接口支持以下公共操作...

    Java面试宝典2010版

    3、编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉...

    基于Python3 逗号代码 和 字符图网格(详谈)

    该字符串包含所有表项,表项之间以逗号和空格分隔,并在最后一个表项之前插入 and 。例如,将前面的spam列表传递给函数,将返回’apples,bananas,tofu,and cats’。但是你的函数应该能够传递给它的任何列表。 代码...

Global site tag (gtag.js) - Google Analytics