字符串到空字符串集合

String to collection with empty String

我有以下字符串:

,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]

但我还想将给定的空字符串放在逗号之前和之间的集合中。

您已手动移动空字符串

if (nextToken != null && nextToken.trim().length() > 0) {

你可能想要这个:

    while (tok.hasMoreTokens()) {
        nextToken = tok.nextToken();
        // if you need replace blank string with empty string, keep next line
        // nextToken = nextToken.trim()
        col.add(nextToken);
    }

nextToken.trim().length() > 0 对于空字符串为 false,因此它们不会被添加到集合中

使用函数式编程:

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(","));
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());
        }
    }
}

}