我面臨與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