Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

0

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

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!