Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a list by chunks in kotlin

Tags:

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?

like image 923
Adam Avatar asked Dec 14 '22 13:12

Adam


1 Answers

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]) }
like image 133
marstran Avatar answered Dec 17 '22 23:12

marstran