如何将逗号分隔的字符串转换为列表? [英] How to convert comma-separated String to List?

查看:165
本文介绍了如何将逗号分隔的字符串转换为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否有任何内置方法可以将逗号分隔的String转换为某个容器(例如数组,列表或向量)?还是我需要为此编写自定义代码?

Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for that?

String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??

推荐答案

将逗号分隔的字符串转换为列表

List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

上面的代码在定义为zero or more whitespace, a literal comma, zero or more whitespace的定界符上拆分字符串,它将把单词放入列表并折叠单词和逗号之间的所有空格.

The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.

请注意,这仅返回数组的包装器:例如,您 不能 来自结果List.remove().对于实际的ArrayList,您必须进一步使用new ArrayList<String>.

Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.

这篇关于如何将逗号分隔的字符串转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆