我面临与In Java, remove empty elements from a list of Strings相同的情况。
我尝试了几乎所有资源,但我每次都得到同样的错误"Exception in thread "main" java.lang.UnsupportedOperationException"
public static void main(String[] args) {
String s = "Hello World. Want to code?";
StringTokenizer tokenizer = new StringTokenizer(s, ".!?");
List<String> words = new ArrayList<String>();
List<String> statement = new ArrayList<String>();
List<List<String>> statements = new ArrayList<List<String>>();
// Seperating words by delimiters ".!?
while (tokenizer.hasMoreTokens()) {
words.add(tokenizer.nextToken());
}
// O/p is {{Hello World},{ Want to code}}
// seperating words by space.
for (int i = 0; i < words.size(); i++) {
String[] temp2 = words.get(i).split("\\s+");
statement = Arrays.asList(temp2);
statements.add(statement);
}
// O/P is {{Hello, World},{, Want, to, code}}
for (List<String> temp : statements) {
// Here i have [, Want, to, code]
// Way-1
Iterator it = temp.iterator();
String str = (String) it.next();
if(str.isEmpty())
it.remove();
// Way-2
temp.removeIf(item -> item.contains(""));
// Way-3
temp.removeAll(Collections.singleton(""));
// Way-4
temp.removeAll(Arrays.asList(""));
// way-5
temp.removeIf(String::isEmpty);
}
}
正如你所看到的,我尝试了4种方式,但没有一种方法可行。 有人有任何想法吗?
答案 0 :(得分:-1)
我想我找到了一个解决方案:将List的数据类型更改为ArrayList。这解决了我的问题:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
String s = "Hello World. Want to code?";
StringTokenizer tokenizer = new StringTokenizer(s, ".!?");
ArrayList<String> words = new ArrayList<String>();
ArrayList<String> statement = new ArrayList<String>();
ArrayList<ArrayList<String>> statements = new ArrayList<ArrayList<String>>();
// Seperating words by delimiters ".!?
while (tokenizer.hasMoreTokens()) {
words.add(tokenizer.nextToken());
}
// O/p is {{Hello World},{ Want to code}}
// seperating words by space.
for (int i = 0; i < words.size(); i++) {
String[] temp2 = words.get(i).split("\\s+");
statement = new ArrayList();
statement.addAll(Arrays.asList(temp2));
statements.add(statement);
}
// O/P is {{Hello, World},{, Want, to, code}}
for (ArrayList<String> temp : statements) {
// Here i have [, Want, to, code]
// Way-2
temp.removeIf(item -> item.equals(""));
System.out.println("array: " + temp);
}
}
}
程序的输出是:
array: [Hello, World]
array: [Want, to, code]