【发布时间】:2017-09-12 13:48:56
【问题描述】:
我面临与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 种方法,但都没有奏效。 有人知道吗?
【问题讨论】:
-
试试
temp.removeIf(String::isEmpty) -
不工作。 :( 我编辑了问题。
-
对不起,我的意思是作为您其他 4 种方式的更好替代方案,而不是作为您问题的答案。答案在重复链接中。
-
在哪里你有
new ArrayList<String>(Arrays.asList(stringArray))??我在代码中只看到两个asList()调用,并且它们都没有 被转换为ArrayList。请注意,list = new ArrayList(); list.add(Arrays.asList(...));不与list = new ArrayList(Arrays.asList(...));相同。也许你应该ArrayList(otherList)构造函数的 read the javadoc,看看它做了什么。 -
是的,我在一分钟内删除了那个问题。我很抱歉,也谢谢。它的工作。 :)
标签: java string list arraylist