Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
How to create a map of string to list

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.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

val mapOfInterest = dataset.groupBy { it.detail }
over 4 years ago · Santiago Trujillo Denunciar

0

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda