Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert two consecutive elements from List to entries in Map?

Tags:

scala

I have a list:

List(1,2,3,4,5,6)

that I would like to to convert to the following map:

Map(1->2,3->4,5->6)

How can this be done?

like image 481
Daniel Wu Avatar asked Dec 14 '22 21:12

Daniel Wu


2 Answers

Mostly resembles @Vakh answer, but with a nicer syntax:

val l = List(1,2,3,4,5,6)
val m = l.grouped(2).map { case List(key, value) => key -> value}.toMap
// Map(1 -> 2, 3 -> 4, 5 -> 6)
like image 114
om-nom-nom Avatar answered Mar 02 '23 00:03

om-nom-nom


Try:

val l = List(1,2,3,4,5,6)
val m = l.grouped(2).map(l => (l(0), l(1))).toMap
like image 35
Jean Logeart Avatar answered Mar 02 '23 00:03

Jean Logeart