Nick Pampoukidis
Nick Pampoukidis

Reputation: 742

Kotlin HashMap contain keys using an array

Is there any way to check a HashMap if it contains a certain set of keys which keys are given in an array. When I try something like the code below it returns false.

map.containsKey(arrayOf("2018-01-16"))

If I try the following code it works but I need to check for the keys and the numbers of keys that I need to search is not fixed.

map.containsKey("2018-01-16")

Upvotes: 4

Views: 6188

Answers (3)

Ilya
Ilya

Reputation: 23164

Map has keys collection, which as every collection implements containsAll method, so you can use it to check whether the keys collection contains all of the keys:

map.keys.containsAll(keysArray.asList())

Upvotes: 2

GoRoS
GoRoS

Reputation: 5375

You could use ArrayList<T> as a key, since it's equals is different as the Array<T> one. Let's see this test:

class ExampleUnitTest {
  @Test
  fun arrayAsKeyTest() {
    val hashMapOne = HashMap<Array<String>, Int>()
    val stringKeysOne1 = arrayOf("a", "b")
    hashMapOne.set(stringKeysOne1, 2)
    val stringKeysOne2 = arrayOf("a", "b")
    // NOT MATCH! As stringKeysOne1 == stringKeysOne2 is false
    assertFalse(hashMapOne.containsKey(stringKeysOne2)) // NOT MATCH

    val hashMapTwo = HashMap<ArrayList<String>, Int>()
    val stringKeysTwo1 = arrayListOf("a", "b")
    hashMapTwo.set(stringKeysTwo1, 2)
    val stringKeysTwo2 = arrayListOf("a", "b")
    // MATCH! As stringKeysTwo1 == stringKeysTwo2 is true (although stringKeysTwo1 === stringKeysTwo2 is false)
    assertTrue(hashMapTwo.containsKey(stringKeysTwo2)) // MATCH
  }
}

Upvotes: 0

zsmb13
zsmb13

Reputation: 89668

You can start from the keys themselves, and use the all function from the standard library:

val map = hashMapOf(...)
val keys = arrayOf("2018-01-16", "2018-01-17", "2018-01-18")
val containsAllKeys = keys.all { map.containsKey(it) }

If you do this a lot and want to have this functionality on the Map type, you can always add it as an extension:

fun <K, V> Map<K, V>.containsKeys(keys: Array<K>) = keys.all { this.containsKey(it) }

val containsAllKeys = map.containsKeys(arrayOf("2018-01-16", "2018-01-17"))

You might also want to overload the extension with another function that takes an Iterable<K> as the parameter.

Upvotes: 4

Related Questions