Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 Respostas
Responde à pergunta

0

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

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda