How to create a map of string to list

Viewed 53

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.

2 Answers

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

val mapOfInterest = dataset.groupBy { it.detail }
Related