safepost
safepost

Reputation: 165

How to make a Map with default values if key is not present?

I want to build a map of array parsing a list of object. When a index of that map as already been added, i need to add the elements of the array that were not added before, else i need to create the new element in the Map.

Let's say we have a csv with data like this

names,nicknames
Tom,tommy;timmy
Sam,sammy
Tom,timmy;mymen

And i want a map like this :

Map["Tom"] = ["tommy", "timmy", "mymen"]
Map["Sam"] = ["sammy"]

I'm quite surprised that there is no native function for that

What's working, but should be improved ? (i have a 400k lines CSV to parse)

    val myObjectList: List<myObject> = beans.parse() /* importing POJOs from csv*/
    val myMap: MutableMap<String,List<String>> = mutableMapOf()

    myObjectList.forEach { entry ->
       if ( myMap[entry.name].isNullOrEmpty()) {
           myMap[entry.name] = entry.nicknames.split(";")
       } else {
           myMap[entry.name]!!.plus(entry.nicknames.split(";"))
       }
    }


    return myMap

Upvotes: 3

Views: 2388

Answers (1)

Laurence
Laurence

Reputation: 1666

Use getOrPut like:

data class MyObject(
        val name: String,
        val nicknames: String
)

fun main() {
    val myObjectList = listOf(
            MyObject("primary", "secondary1;secondary2"),
            MyObject("primary", "secondary3")
    )
    val nameToNicks = mutableMapOf<String, MutableList<String>>()

    myObjectList.forEach { myObj ->
        nameToNicks.getOrPut(myObj.name, {mutableListOf()}) .addAll(myObj.nicknames.split(";"))
    }

    print(nameToNicks)
}

Upvotes: 3

Related Questions