Reputation: 107
var listOfNums = listOf(1,9,8,25,5,44,7,95,9,10)
var mapOfNums = listOfNums.map { it to it+1 }.toMap()
println(mapOfNums)
result
{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}
Upvotes: 3
Views: 562
Reputation: 439
We can step over every second index and map listOfNums[it] to listOfNums[it+1]
val listOfNums = listOf(1,9,8,25,5,44,7,95,9,10)
val mapOfNums = mutableMapOf<Int, Int>()
(listOfNums.indices step 2).forEach {
mapOfNums[listOfNums[it]] = listOfNums[it + 1]
}
println(mapOfNums)
EDIT: Another better solution suggested by ephemient:
(1..listOfNums.lastIndex step 2).associate { listOfNums[it - 1] to listOfNums[it] }
Elegant!
Upvotes: 1
Reputation: 27971
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 = list.zip(list.drop(1))
.filterIndexed { index, pair -> index % 2 == 0 }
.toMap())
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 }
Upvotes: 6
Reputation: 8386
With the help of RxJava
import io.reactivex.Observable
...
val listOfNums = listOf(1,9,8,25,5,44,7,95,9,10)
val mapOfNums = Observable.fromIterable(listOfNums)
.buffer(2)
.map { it[0] to it[1] }
.collect(
{ mutableMapOf<Int, Int>() },
{ map: MutableMap<Int, Int>, (first, second) -> map.put(first, second) }
)
.blockingGet()
println(mapOfNums)
// {1=9, 8=25, 5=44, 7=95, 9=10}
Upvotes: 1