Kotlin: Collections Part 3 — Map

MJ Manaog
3 min readJul 4, 2020

--

In maps, types of both keys and values are user-defined. Key-based access to map entries enables various map-specific processing capabilities from getting a value by key to separate filtering of keys and values.

Map

Let’s take a look first at the Map interface:

Map
  • Map doesn’t implement the Collection interface unlike List and Set
  • Map stores key-value pair or entries
  • Keys must be unique and Values may contain any possible value you would like
  • Map is immutable

Map Declaration

  • Line 10 — we declared a class named LoL and has two strings and a list of string as a parameter.
  • Line 12, 14, and 16 — we have a private method that returns a list of items for our three champs build (Note: I’m not a pro LoL player, this is for example only ✌️)
  • Line 2 — we’ve declared an immutable map here, and put some values that were fit for the explicit key-value type <Int, Lol>
  • Line 5 — we specifically print the build for our key: 2. Take note that the value inside the brackets should be a key to your map entries. This is the same with: lolChamps.get(2)?.build
  • Line 6 — we just iterate inside our map to get the names.

Mutable Map

Mutable Map
  • MutableMap implements the Map interface
  • Almost the same with Map but the big difference is obviously, MutableMap is mutable, which means you can add or remove any entries you would like.

MutableMap Declaration

  • Line 2 — we’ve declared a mutable map here
  • Line 6— if you wish to add another entry to your mutable map, you can use put. But observe the declaration here, instead of using the keyword to we used , because put method requires two parameters, key and value.
  • Line 7 — we just iterate through our mutable map to get its value
  • Line 11 — here, we’re checking the class of the instance we’re getting from the mutableMapOf function and its : class java.util.LinkedHashMap
  • So mutableMapOf uses LinkedHashMap so we can easily convert from list to a set to a map.

But if you want to use HashMap only, see Line 13.

  • Line 13 — you can also use hashMapOf since it’s also mutable.
  • Line 17 — we’ve added new entry with the key Basic Skin and a value of 520 . Yes, it’s the same with put method. Either way, it’ll work. But if you want your code to be more readable for the others, I suggest you use put instead.
  • Line 22 — If we check the class of the hashMapOf this is what we’re going to get: class java.util.HashMap

You can use Map in different ways, especially if you want to filter or give your data a unique identification. It’s really helpful.

It’s quite a lot, but if you finished reading this, thank you!

--

--

MJ Manaog
MJ Manaog

Responses (1)