【问题标题】:How can I add and remove items from my set concurrently? [duplicate]如何同时从我的集合中添加和删除项目? [复制]
【发布时间】:2023-04-06 12:54:01
【问题描述】:

我正在尝试从推文中删除停用词,我首先添加标记,然后循环它们以查看它们是否与停用词集中的单词匹配,如果是,则删除它们。我得到一个 Java ConcurrentModificationErorr。这是一个sn-p。

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());

【问题讨论】:

  • 你得到的不是 ConcurrentModificationErorr(原文如此)。这是一个ConcurrentModificationException。只要在这里搜索 ConcurrentModificationException 就会引出许多类似的问题。
  • 我使用重复的 Set 解决了它。检查我的答案。

标签: java


【解决方案1】:
for (String word : tweets) {
                        if (stopwords.contains(word)) {
                        tweets.remove(word);
                        }
                    }

上面的代码导致并发修改异常,因为在迭代时修改集合,以避免它像下面这样使用

   for(String word : new HashSet<String>(tweets)) {
                        if (stopwords.contains(word)) {
                        tweets.remove(word);
                        }
                    }

【讨论】:

  • 无法从对象转换为字符串
  • put new HashSet(tweets);
  • 现在编辑了答案以避免编译时错误..
  • 我使用重复的 Set 修复了它,见下文。
【解决方案2】:

我使用重复的 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);
                    }
                }

【讨论】:

  • 这也是使用另一个临时集,比如我的代码
猜你喜欢
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 2015-10-05
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多