我面临与In Java, remove empty elements from a list of Strings相同的情况。 我几乎尝试了一切,从资源,我能得到,但每次我得到同样的错误"Exception in thread "main" java.lang.UnsupportedOperationException"
无法从字符串ArrayList中删除空元素
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种方式,他们都不工作。 有人有什么想法吗?
尝试'temp.removeIf(字符串::的isEmpty)' – Andreas
不工作。 ( 我编辑的问题 – user252514
对不起,我的意思是作为一种更好的替代你的4种其他方式,而不是作为你的问题的答案。答案在重复的链接。 – Andreas