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

191
Views
How to map a list by chunks in kotlin

I often end up with data sources like (pseudo code below, not any specific syntax, it is just to illustrate):

list = {
  "XLabel", 
  "XDescription", 
  "YLabel", 
  "YDescription", 
  "ZLabel", 
  "ZDescription"
}

desired output is:

list = { 
  MyClass("XLabel", "XDescription"), 
  MyClass("YLabel", "YDescription"), 
  MyClass("ZLabel", "ZDescription")
}

Is there anything more clean than to do a fold(), and fold it into a new list? I've also rejected doing something weird like list.partition().zip()

I basically want a more powerfull map that would work like mapChunks( it1, it2 -> MyClass(it1, it2)) where the chunking is part of the function so it gets easy and nice. (My example has the list in chunks of two, but 3 is also a prevalent use case.)

Does this function exist? Or what is the most idiomatic way to do this?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can use the chunked function, and then map over the result. The syntax gets very close to what you wanted if you destructure the lambda-argument:

list.chunked(2)
    .map { (it1, it2) -> MyClass(it1, it2) }
    // Or use _it_ directly: .map { MyClass(it[0], it[1]) }
over 4 years ago · Santiago Trujillo Report

0

I think the windowed method should do what you want.

lst.windowed(size = 2, step = 2, partialWindows = false) { innerList -> MyClass(innerList[0], innerList[1]) }

You can also use chunked but it calls windowed under the hood. But with chunked you can get lists that have fewer elements than you were expecting

EDIT to answer @android developer's question about getting the indexes of the list

val lst = listOf(7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
val windowedList = lst.mapIndexed { index, it -> index to it }
    .windowed(size = 2, step = 2, partialWindows = false) {
        it[0].first
    }
println(windowedList)

Would output

[0, 2, 4, 6, 8]
over 4 years ago · Santiago Trujillo Report

0

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/chunked.html

Chunked returns a sub list of the size you specify

This is the API call you want

considering your list is in pairs of 2 you can do this

list.chunked(2)  //List<List<String>>
    .map{MyClass(it[0], it[1]} //list<MyClass>
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!