thePanthurr
thePanthurr

Reputation: 114

Equivalent of Iterator.Remove in Kotlin HashMap?

Sorry if this is a dumb question-- but in java I am used to doing something like the following:

Iterator whatever = entrySet.iterator()
while (whatever.hasNext()) {
    for (int i = 0; i < 4; i++) {
        if (i == 3) {
            whatever.remove(whatever.next().key)
        }
    }
}

(Pseudocode and the logic makes no sense)

However, the "remove" function doesn't exist for a hashmap in Kotlin. I understand you can use removeIf for a single condition, but I want to loop through a bunch of different conditions before I decide what to remove-- all without dodging a concurrent modification exception.

What is the way to do this in Kotlin?

Thank you for your time!

Upvotes: 6

Views: 4061

Answers (2)

Sam Chen
Sam Chen

Reputation: 8917

val addedItems = HashMap<String, Int>()

fun main() {
    addedItems["Apple"] = 3
    addedItems["Lemon"] = 4

    println(addedItems)

    addedItems.values.removeAll { it == 4 }        //or remove by keys ".keys.removeAll{}
    println(addedItems)
}

Output:

{Apple=3, Lemon=4}
{Apple=3}

Upvotes: 0

KollKode
KollKode

Reputation: 433

In Kotlin you can use removeIf on mutable map entries without accessing the iterator explicitly.

val entrySet = HashMap<String, String>()
entrySet.entries.removeIf { 
  // some predicate 
}

will remove all entries that match the predicate

Upvotes: 9

Related Questions