Hash Tables in Kotlin

H

Data structures are important topics in any kind of software development, but most of the explanations surrounding them are based in Java. The advantage of Android development is that it was initially done in Java, but in the more recent years, Kotlin has been the preferred language for development. For this reason, it’s important to understand and take the classical and broad Java knowledge into modern programming languages. This is important for a number of reasons, among which we could mention: knowing data structures gives us strong programming bases, makes coding easier, helps us optimize execution time and memory, and also they are usually asked in technical interviews!

Basics

As mentioned above, Kotlin is based on Java’s data structure. Java itself had among its vast amount of versions an implementation of HashTable and another for HashMap. Kotlin, on the other hand, decided to use HashMap, because they are roughly equivalent.

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

Android HashMap documentation

An important thing to note is that this HashMap class has a constant time performance, which is known in O-notation as O(1), but for the worst case it may get to O(N). Although it is important to note that some implementations of hash maps use self-balancing binary search trees and those are O(log N) for the worst case, but this is not the case for the Kotlin implementation.

KVP: Key-Value Pair

The term Key-Value pair is often used in software development, but with so many acronyms it is important to know most of the times KVP in this context refers to this term. In short, it refers that you have two associated objects, one represents the key, and the other the associated value. This gives one very important advantage of this Data Structure: when you have a key and a value there is no need to store items in a particular place in memory because as long as you reference the key, you will get the value. Derived from the last point, it is also important to know that items will never be in order.

To make the above clear it is important to compare the HashMap Data Structure with arrays. If you know this other data structure, you will know items are stored on a zero-index base, which means each item will be represented by a numeric value starting in zero. In the case of arrays, the index numbers are the keys, and they will be stored in order in the memory because otherwise, the key would give you a different value every time.

Representation

The way Kotlin represents HashMap is very straight forward:

HashMap<key, value> or HashMap<K, V>

Constructors

In Kotlin HashMap there are 4 constructors:

HashMap() 
HashMap(initialCapacity: Int, loadFactor: Float) HashMap(initialCapacity: Int)
HashMap(original: Map <out K, V> )

For the first one, there is no need to add anything. Just an empty constructor and you have your map, KVPs can be added later.

The second and third have two parameters:

  1. initialCapacity: if you know how many items you will need since the beginning you can specify that.
  2. loadFactor: this one defines at what rate you want the HashMap to grow. If you started with 4 items, a load factor of 0.50 would mean that once 2 out of those 4 items are filled the size will increase.

For the last one, you create a HashMap from a Map, so you can operate on it.

HashMap Example

Let’s say you own a vinyl shop (I know! Oldie!), and customers have a hard time finding titles, so you assign a number to each of them, and order them from the lowest to the highest number. You then create a hashmap to search for them. The code will look like the following:

package com.evanamargain.hashmap fun main() { 
val records = HashMap<String, Int>() records["Michael Jackson"] = 30
records["The Beatles"] = 20
records["Rolling Stones"] = 70 for ((k, v) in items) {
println("$k = $v")
}
}

What kind of Algorithmic problems can be solved with HashMaps?

  1. Knowing if one array is a subset of another
  2. Finding the largest subarray with certain characteristic
  3. Summing pairs of numbers

As you can see HashMaps are simple and useful tools for development in Kotlin, if you are already a developer, most likely you can think of a couple of times you have used them in the past. Otherwise, you can now start doing it.

If you liked the content on this post, please follow me. Visit my webpage evanamargain.com or more specifically my blog. You can also buy me a coffee to support me!

Until next time!

Evana Margain Puig

If you need any services regarding mobile apps please come to my webpage, evisoft.mx or drop me a line contacto@evisoft.mx.

About the author

Evana Puig

Add Comment

By Evana Puig

Evana Puig

Get in touch

Mobile Developer expert in Android and iOS, with 10 years of experience. Visit me at evanapuig.com. Author, and topic master at raywenderlich.com