Hoinzey

Javascript. Kotlin. Android. Java

Kotlin: associate helpers

One of these helpers came to my attention during a recent code review and I thought it was handy, so I'm recording it. All the following allow you to easily turn a list into a map using an object field as the key, or the object as a key to a field.


associate


Pass in a transform to get back a Map of the first half of the email addresses to the second half (for whatever reason).


                    
    fun run() {
        val usersList = mutableListOf<User>()
        usersList.apply {
            add(User(24, "Hoinzey", "hoin@zey.dev"))
            add(User(631, "Bear", "be@ar.dev"))
            add(User(2735, "Towers", "tow@ers.dev"))
        }

        val splitEmail = usersList.associate {
            it.email.split("@")
                .let { (firstHalf, secondHalf) -> firstHalf to secondHalf }
        }
        println(splitEmail)
    }
    //{hoin=zey.dev, be=ar.dev, tow=ers.dev}
                

associateBy


In this example we are passing the field we want to use as our key in the map to the object as the value.


                    
    fun run() {
        val usersList = mutableListOf<User>()
        usersList.apply {
            add(User(24, "Hoinzey", "hoin@zey.dev"))
            add(User(631, "Bear", "be@ar.dev"))
            add(User(2735, "Towers", "tow@ers.dev"))
        }

        val userMap = usersList.associateBy { it.id }
        println(userMap)
    }
    //{24=User(id=24, name=Hoinzey, email=hoin@zey.dev), 
    //631=User(id=631, name=Bear, email=be@ar.dev), 
    //2735=User(id=2735, name=Towers, email=tow@ers.dev)}
                

associateWith


Here we are doing the opposite, where the object is the Key and the value is the field we pass in.


                    
    fun run() {
        val usersList = mutableListOf<User>()
        usersList.apply {
            add(User(24, "Hoinzey", "hoin@zey.dev"))
            add(User(631, "Bear", "be@ar.dev"))
            add(User(2735, "Towers", "tow@ers.dev"))
        }
        
        val userToEmail = usersList.associateWith { it.email }
        println(userToEmail)
    }
//{User(id=24, name=Hoinzey, email=hoin@zey.dev)=hoin@zey.dev, 
//User(id=631, name=Bear, email=be@ar.dev)=be@ar.dev, 
//User(id=2735, name=Towers, email=tow@ers.dev)=tow@ers.dev}