Ali Urz Ali Urz -3 years ago 146
Java Question

Change a list to map in Kotlin while customize this convert

var listOfNums = listOf(1,9,8,25,5,44,7,95,9,10)
var mapOfNums = { it to it+1 }.toMap()


{1=2, 9=10, 8=9, 25=26, 5=6, 44=45, 7=8, 95=96, 10=11}

while I need this result, it adds contents of next element to the current element while I need to map current element to next element

my goal result

{1=9, 8=25, 5=44, 7=59, 9=10}

Answer Source

For Kotlin 1.1:

First, use zip to create a list with adjacent pairs. Then you drop every other pair, before converting it to a Map. Like this:

val list = listOf(1,9,8,25,5,44,7,95,9,10)
val mapOfNums =
                    .filterIndexed { index, pair -> index % 2 == 0 }

For Kotlin 1.2:

Kotlin 1.2 brings the chunked function which will make this a bit easier. This function divides the list up in sublists of the given length. You can then do this:

val list = listOf(1,9,8,25,5,44,7,95,9,10)
val mapOfNums = list.chunked(2).associate { (a, b) -> a to b }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download