4

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")
2
  • Do you want to return true if the map contains all of the keys or just any of it? Commented Dec 16, 2017 at 19:21
  • If it contains all the keys. Commented Dec 16, 2017 at 19:22

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

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.