How to optimize work with HashMap in Kotlin?

everybody. Today I wrote next code. Looks like it work, but I wonder, is it right way to do what I want. I have HashMap with listeners as keys and boolean as value that determine: is listener already received last update. Is it right way I reset HashMap?

private val listenersUpdateState: HashMap<WeakReference<IStatusesListener>, Boolean> = HashMap()

private fun setAllListenersToReadyToUpdate() {
    listenersUpdateState.keys.forEach { key -> 
        listenersUpdateState[key] = false
    }
}

Upvotes: 2

Views: 414

Answers (2)

Animesh Sahu
Animesh Sahu

Reputation: 8106

You could use a handy function like Map.mapValues()

Example:

private val listenersUpdateState: MutableMap<WeakReference<IStatusesListener>, Boolean> = mutableMapOf()

private fun setAllListenersToReadyToUpdate() = listenersUpdateState.mapValues { false }

This will help not to index map again and again by map[key] keyword which will improove the performance!

EDIT:

The above code works for formulating a new map with all values set to false but to repace all values of original map see the below code

private fun setAllListenersToReadyToUpdate() =
    listenersUpdateState.entries.onEach { it.setValue(false) }

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93739

If you're targeting Java 8 or above, you can use replaceAll:

listenersUpdateState.replaceAll { _, _ -> false }

Alternatively, you can just call clear() on the map, and when you retrieve values, default to false when the value is not present:

fun isUpdated(someRef: WeakReference<IStatusesListener>) = listenersUpdateState[someRef] ?: false

Upvotes: 0

Related Questions