如果条件取决于迭代器所基于的对象的 属性,如何从迭代器中删除元素?

How to remove element from iterator if condition depends on property of the object the iterator is based on?

让我详细说明:

我需要能够遍历对象列表。每个对象都有一个 属性 这是一个列表,我必须检查该列表是否包含不在另一个列表中的任何元素。

当我尝试使用嵌套 for 循环来实现它时,它一直给我并发修改异常,所以我尝试使用迭代器,但现在我卡住了,因为如果我根据列表创建迭代器的对象,我无法访问单个对象的属性然后进行迭代。

这是我试图完成的一些示例代码:

for (preference in preferencesWithRestaurant) {
    for (restaurantID in preference.restaurantIDs) {
        // One method I tried using
        preferencesWithRestaurant.removeIf{ !listOfIds.contains(restaurantID) }

        /* alternate method I tried using
        if (!listOfIds.contains(restaurantID)) {
            preferencesWithRestaurant.remove(preference)
        }
        */

    }
}

如果您可以替换 preferencesWithRestaurant 的值或将结果存储在另一个变量中,那么您可以 filter it:

preferencesWithRestaurant = preferencesWithRestaurant.filter { preference ->
    preference.restaurantIDs.all { it in listOfIds }
}

根据 preferencesWithRestaurant 的确切类型,您可能需要将其转换为正确的类型,例如最后调用 toMutableList()

如果你更喜欢就地修改preferencesWithRestaurant,那么你可以使用retainAll()(感谢@Tenfour04):

preferencesWithRestaurant.retainAll { preference ->
    preference.restaurantIDs.all { it in listOfIds }
}

或者,您可以保留原来的方法,但使用可变迭代器在迭代时删除项目:

val iter = preferencesWithRestaurant.listIterator()
for (preference in iter) {
    for (restaurantID in preference.restaurantIDs) {
        if (!listOfIds.contains(restaurantID)) {
            iter.remove()
            break
        }
    }
}