如何将逗号分隔的字符串转换为ArrayList? [英] How to convert comma-separated String to ArrayList?
本文介绍了如何将逗号分隔的字符串转换为ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中有什么内置方法,允许我们将逗号分隔的字符串转换为某个容器(例如array,List或Vector)?或者我需要为此编写自定义代码?
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";
ArrayList<String> items = //method that converts above string into list??
推荐答案
将逗号分隔字符串转换为ArrayList
Convert comma separated String to ArrayList
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
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.
这篇关于如何将逗号分隔的字符串转换为ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文