迭代器删除仍然留下集合中的元素

时间:2017-04-08 22:19:24

标签: java iterator set

我有这段代码:

            for (Iterator<RuleConditionBl> iterator = ruleConditionBls.iterator(); iterator.hasNext();) {
                RuleConditionBl ruleConditionBl =  iterator.next();
                if (ruleConditionBl.equals(ruleCondition)) {
                    iterator.remove();
                }
            }
            if (ruleConditionBls.size() == 0)
            {
                countryToNonSplittedRules.remove(country);
            }

我在执行此行之前和之后看到ruleConditionBls.size == 1 iterator.remove();

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

JB Nizet回答后,我更改了我的代码,现在可以正常运行:

It uses the current hashCode to find the bucket where the element is located, and since the hashCode has changed, it doesn't find it.

   Set<RuleConditionBl> ruleConditionBls = countryToNonSplittedRules.get(country);
            if (ruleConditionBls != null) {

                final Set<RuleConditionBl> collect = ruleConditionBls.stream().filter(condition -> !condition.equals(ruleCondition)).collect(Collectors.toSet());
                if (collect.size() == 0)
                {
                    countryToNonSplittedRules.remove(country);
                }
                else
                {
                    countryToNonSplittedRules.put(country, collect);
                }
            }