Home > Software engineering >  How to create a map of string to list
How to create a map of string to list

Time:03-10

I have a JSON data in the given format:

dataset = [
    { 'name': 'Sayantan', 'section': 'A', 'detail': 'complete' },
    { 'name': 'Charu', 'section': 'B', 'detail': 'complete' },
    { 'name': 'Sanhati', 'section': 'C', 'detail': 'inprogress' },
]

I want to convert it into a map of <String, List<>> and get it in the following format:

{'complete': [{'detail': 'complete', 'name': 'Sayantan', 'section': 'A'},
              {'detail': 'complete', 'name': 'Charu', 'section': 'B'}],
 'inprogress': [{'detail': 'inprogress', 'name': 'Sanhati', 'section': 'C'}]}

I do not have much experience in Kotlin, I have mostly worked with such cases in Python and I have managed to write the following:

val mapOfInterest = mutableMapOf<String, List<DataResource>>()
for (data in datasets) {
  val mapKey = data.detail
  if (!mapOfInterest.containsKey(mapKey)) {
    if (mapKey != null) {
      mapOfInterest[mapKey] = listOf(data)
    } else {
      mapOfInterest[mapKey] // I am stuck here
    }
  }
}

I am unable to add data to the map key-value by using add(), any idea or clue would be helpful.

CodePudding user response:

There is a stdlib function for what you need called groupBy:

val mapOfInterest = dataset.groupBy { it.detail }

CodePudding user response:

In Kotlin, Collections are not mutable by default: https://kotlinlang.org/docs/collections-overview.html. So List does not have an add() Method.

You could use mutableListOf() instead, but the "right" way to do it in Kotlin is, as Joffrey already pointed out, to use the standard function groupBy() https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html

  • Related