我有一个变体列表,其中每个变体都有颜色列表。我想检查每个变体是否具有过滤器的颜色,如果没有,我想从变体列表中删除该变体。当我尝试删除时出现错误:java.util.ConcurrentModificationException 这是我尝试过的:
list.map { variant ->
variant.variantColors.map { color ->
if (color != filterModel.color) {
list.removeIf { color != filterModel.color }
}
}
}
和:
list.map { variant ->
variant.variantColors.map { color ->
if (color != filterModel.color) {
list.removeAll { color != filterModel.color }
}
}
}
和:
val iterator = list.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
val iteratorSec = item.variantColors.iterator()
while (iteratorSec.hasNext()) {
val itema = iteratorSec.next()
if (itema != filterModel.color)
iterator.remove()
}
}
答案 0 :(得分:2)
使用列表过滤器功能这样的概念
fun main()
{
val myList : MutableList<ColorInfo> = mutableListOf(
ColorInfo(color = "red",colorcode = "1111"),
ColorInfo(color = "green",colorcode = "1123"),
ColorInfo(color = "yellow",colorcode = "1134")
)
val filteredList = myList.filter { !it.color.equals("red") }
println(filteredList.toString())
//out put is [Event(color=green, colorcode=1123), Event(color=yellow, colorcode=1134)]
}
data class ColorInfo(var color : String,var colorcode : String)
答案 1 :(得分:0)
发生这种情况是因为您尝试在map()
回调中对列表进行更改时对列表进行迭代。
为了避免这种情况,您应该先调用removeAll()/ removeIf():
class Variant(val colors: List<Int>)
fun main() {
val badColor = 2
val variants = mutableListOf(
Variant(listOf(1, 2, 3)),
Variant(listOf(2, 4, 6)),
Variant(listOf(3, 5, 7)))
// try removeAll()
variants.removeAll {
it in variants.filter {variant ->
badColor in variant.colors
}
}
// or removeIf()
variants.removeIf {
badColor in it.colors
}
print(variants)
}