April 22, 2024

Stock Bitcoin

Bitcoin News and something more!

HashMap in Kotlin – Most Useful Methods

hashmap kotlin

A HashMap in Kotlin is a data structure, the same as several programming languages to have a list (array) of keys with their respective values.

The way in which a hashmap is used is very simple, everything can be managed through a direct access to the value (value) accessing from its key (key), both in operations of reading, assignment or modification of the value.

How to create a HashMap in Kotlin

The HashMap declaration in Kotlin is very simple and can be declared as a class variable or within a function as follows:

var miHashMap: HashMap = HashMap()

The type_key is the type that the HashMap keys will have, to access their respective value, and the type_value is the type of value. For example, if we want to make a HashMap for a userID and username system, the HashMap would be declared as follows:

var usersList: HashMap = HashMap()

Operations with HashMap

The use of HashMap is totally dynamic, once it has been declared, that is, you can add elements, change values, delete elements, etc. directly accessing the item through its key. Let’s see some examples:

Add or modify a new item

It is sufficient to assign the value to the desired key (as well as a change in value). For example, if we want to assign Francisco’s name to user 10, we do it as follows:

usersList[10] = “John”

We can compare if two elements are equal directly using compareTo

    Timber.d("User is Peter")
    Timber.d("User is not Peter")

Where by the assignment of the previous paragraph, the result would be false.

Reading an item

It is enough to obtain the desired key value.

var currentUser = usersList[10]

Check if an item exists

We validate by means of containsKey if the key exists within the array

    Timber.d("User 10 exists")
    Timber.d("User 10 does not exist")

Remove an item from the Kotlin HashMap

We use remove, indicating the key of the element that we want to remove.


Clear all elements from HashMap in Kotlin

If we want to remove all the elements of the HashMap, that is, empty it, we can do it using the following line of code:


Get the keys that contain a specific value

To obtain an array with the keys that contain a particular value, we use filterValues. In this case we obtain an array, which we can access directly by mapping the results as follows:

val keys = usersList.filterValues{it == "your_value"}.keys
for(i in keys)
    Timber.d("Key found: $i")