Java 如何从集合中同时添加和删除项目?
我试图从tweet中删除停止词,我首先添加标记,然后循环查看它们是否与停止词集中的词匹配,如果是,则删除它们。我得到一个JavaConcurrentModificationError。这里有一个片段Java 如何从集合中同时添加和删除项目?,java,Java,我试图从tweet中删除停止词,我首先添加标记,然后循环查看它们是否与停止词集中的词匹配,如果是,则删除它们。我得到一个JavaConcurrentModificationError。这里有一个片段 while ((line = br.readLine()) != null) { //store tweet splits LinkedHashSet<String> tweets = new LinkedHashS
while ((line = br.readLine()) != null) {
//store tweet splits
LinkedHashSet<String> tweets = new LinkedHashSet<String>();
//We need to extract tweet and their constituent words
String [] tweet = line.split(",");
String input =tweet[1];
String [] constituent = input.split(" ");
//add all tokens in set
for (String a : constituent) {
tweets.add(a.trim());
}
System.out.println("Before: "+tweets);
//replace stopword
for (String word : tweets) {
if (stopwords.contains(word)) {
tweets.remove(word);
}
}
System.out.println("After: "+tweets);
//System.out.println("Tweet: "+sb.toString());
while((line=br.readLine())!=null){
//存储推文拆分
LinkedHashSet tweets=新LinkedHashSet();
//我们需要提取tweet及其组成词
String[]tweet=line.split(“,”);
字符串输入=tweet[1];
String[]component=input.split(“”);
//在集合中添加所有令牌
for(字符串a:成分){
添加(a.trim());
}
System.out.println(“Before:+tweets”);
//替换停止字
for(字符串字:tweets){
if(stopwords.contains(word)){
删除(单词);
}
}
System.out.println(“在:+tweets之后);
//System.out.println(“Tweet:+sb.toString());
上面的代码导致并发修改异常,因为在迭代时修改集合,以避免使用它,如下所示
for(String word : new HashSet<String>(tweets)) {
if (stopwords.contains(word)) {
tweets.remove(word);
}
}
for(字符串字:新哈希集(tweets)){
if(stopwords.contains(word)){
删除(单词);
}
}
我用一个重复的LinkedHashSet解决了这个问题
LinkedHashSet<String> tweets_set = new LinkedHashSet<String>(tweets);
System.out.println("Before: "+tweets);
//replace stopword
for (String word : tweets_set) {
if (stopwords.contains(word)) {
tweets.remove(word);
}
}
LinkedHashSet tweets\u set=新的LinkedHashSet(tweets);
System.out.println(“Before:+tweets”);
//替换停止字
for(字符串字:tweets_set){
if(stopwords.contains(word)){
删除(单词);
}
}
你可以看到你得到的不是ConcurrentModificationError(原文如此)。这是一个ConcurrentModificationException。在这里搜索ConcurrentModificationException会导致许多类似的问题。我使用了一个重复集解决了它。检查我的答案。无法从对象转换为Stringput新哈希集(tweets);现在编辑答案以避免编译时错误..我使用了一个重复集修复了它,请参见下文。这也使用了另一个临时集,如我的代码
LinkedHashSet<String> tweets_set = new LinkedHashSet<String>(tweets);
System.out.println("Before: "+tweets);
//replace stopword
for (String word : tweets_set) {
if (stopwords.contains(word)) {
tweets.remove(word);
}
}