how to allow duplicate keys in Hashmaps Kotlin?

Viewed 3095

I need a kotlin code for a hashmap that allows duplicate keys

class HashMap<K, V> : MutableMap<K, V>
2 Answers

What you want can be achieved with a List that contains Pairs:

val mapWithDuplicateKeys = listOf(
            KEY1 to VALUE1
            KEY1 to VALUE2
            KEY2 to VALUE3
    )

Or simply by adding to the list:

val mapWithDuplicateKeys=mutableListOf<Pair<String,String>>()
mapWithDuplicateKeys.add(KEY1 to VALUE1)
mapWithDuplicateKeys.add(KEY1 to VALUE2)
mapWithDuplicateKeys.add(KEY2 to VALUE3)

Checking for containing entries would be like:

mapWithDuplicateKeys.any { it.first==KEY1 && it.second==VALUE1 } //true
mapWithDuplicateKeys.any { it.first==KEY1 && it.second==VALUE3 } //false

Removing entries would be like:

mapWithDuplicateKeys.removeIf { it.first == KEY1 && it.second == VALUE1 }

Retrieving entries would be like:

val valuesMatchingKEY1 = mapWithDuplicateKeys.filter { it.first== KEY1 }.map{it.second}

Of course you could always make a new class and wrap all the above functionality with simple methods :)

Supposing your keys and values are both Strings, you could make a MutableMap<String, MutableList<String>>.

val eventsBySubject = mutableMapOf<String, MutableList<String>>()

// Adding a value "physics" for key "test":
eventsBySubject.getOrPut("test", ::mutableListOf).add("physics")

// Getting all the values for a key "quiz":
val quizzes: List<String> = eventsBySubject["quiz"].orEmpty()

// Removing a single value "lab" for key "test":
eventsBySubject["test"]?.remove("lab")
Related