How to convert data class to map

Viewed 2913

I tried convert to data class to map. (Under the code is just example code)

data class User (
  val name : String = "",
  val age : Int = 0,
  val deviceGroup: MutableSet<DeviceGroup> = mutableSetOf()
)
data class DeviceGroup (
  val name : String = "",
  val deviceLink : MutableSet<DeviceLink> = mutableSetOf()
)
data class DeviceLink (
  val id : Int = 0,
  val device : Device
)
data class Device (
  val devId : Int = 0,
  val name : String = ""
)

fun main (request : HttpServletRequest) {
  val currentUser = request.session.getAttribute("user") as User
  val data = userRepository.findByName(currentUser.name)
  
  // return currentUser
  // result is {name="test", age=17, deviceGroup = [{name="group1"}, {name="group2"}]}
  
  // I want deserialization data class to Map
  val response = data.deviceGroup.toMap()
  
  response.deivceGroup.forEach {
    // And add new key, pair
    it.add(Map<String, MutableSet<Device>>("devices", mutableSetOf()))

    // Lastly, I want put in the value    
deviceGroupRepository.findByName(it.name).deviceLink.forEach {
      it.devices.add(this)
    }
  }
  
  return response
}

if just return the data value, that's result is "{name="test", age=17, deviceGroup = [{name="group1"}, {name="group2"}]}"

How to convert to data class to Map object and add new key pair?

1 Answers

Use associate to turn a collection into a Map

The Kotlin standard library provides a function called associate which will take a collection of objects and transform them into a map. It takes one argument, which is a function specifying what the keys and values of the map should be.

For example, in your case, you would call it like this:

val response = data.deviceGroup.associate { it.name to it.deviceLink }

It will return a Map<String, MutableSet<DeviceLink>> where the key is the name of the device group and the value is the deviceLink set.


The easiest way to add new values is simply to append them with the + operator.

val response = data.deviceGroup.associate { 
    it.name to it.deviceLink 
} + mapOf("device" to emptySet())

If you need more control than that, you could use .toMutableMap() so new entries can be added using put.

val response = data.deviceGroup.associate { 
    it.name to it.deviceLink 
}.toMutableMap()
response.put("device", emptySet())
Related