0

I have list of variants where every variant has list of colors. I want to check for every variant if has color from filter and if no, I want to remove that variant from list of variants. When I tried to remove I get error: java.util.ConcurrentModificationException This is what I tried:

list.map { variant ->
    variant.variantColors.map { color ->
        if (color != filterModel.color) {
            list.removeIf { color != filterModel.color }
        }
    }
}

and:

list.map { variant ->
    variant.variantColors.map { color ->
        if (color != filterModel.color) {
            list.removeAll { color != filterModel.color }
        }
    }
}

and:

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()
    }
}
1
  • Please share the full crash log/stacktrace. Commented Apr 9, 2019 at 13:13

2 Answers 2

2

Use list filter function like this for your concept

 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)
Sign up to request clarification or add additional context in comments.

Comments

0

It happens because you're trying mutate you list inside map() callback while it's iterating around list. To avoid it you should call removeAll()/removeIf() first:

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.