我有以下字符串:
,Test1,,Test2
并想将其放入这样的集合中:
[],[Test1],[],[Test2]
我的代码
public static void stringToCollectionEmpty(String separator, String str, Collection col) {
if (str != null) {
StringTokenizer tok= new StringTokenizer(str, separator);
String nextToken;
while (tok.hasMoreTokens()) {
nextToken = tok.nextToken();
if (nextToken != null && nextToken.trim().length() > 0) {
col.add(nextToken.trim());
}
}
}
}
我只得到
[Test1],[Test2]
但是我想将逗号之前和之间的给定空字符串放入集合中。
最佳答案
使用函数式编程:
public static void main(String[] args) {
String s = ",Test1,,Test2";
List<String> collect = Arrays.stream(s.split(","))
.map(t -> "[" + t + "]")
.collect(Collectors.toList());
System.out.println(collect);
}
输出:
[[], [Test1], [], [Test2]]
如果您不需要在 String
周围使用额外的括号,您可以只使用:
List<String> collect = Arrays.asList(s.split(","));
关于java - 字符串到带有空字符串的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58506687/