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

淺唱寂寞╮ 提交于 2021-01-27 07:27:50

问题


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?


回答1:


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)



回答2:


Try:

val l = List(1,2,3,4,5,6)
val m = l.grouped(2).map(l => (l(0), l(1))).toMap



回答3:


if the list is guaranteed to be of even length:

val l = List(1,2,3,4,5,6)
val m = l.grouped(2).map { x => x.head -> x.tail.head }.toMap
// Map(1 -> 2, 3 -> 4, 5 -> 6)

but if list may be of odd length, use headOption:

val l = List(1,2,3,4,5,6,7)
val m = l.grouped(2).map(x => x.head -> x.tail.headOption).toMap
// Map(1 -> Some(2), 3 -> Some(4), 5 -> Some(6), 7 -> None)



回答4:


Without using grouped that appears ubiquitous in the answers so far.

scala> val l = (1 to 6).toList
l: List[Int] = List(1, 2, 3, 4, 5, 6)

scala> l.zip(l.tail).zipWithIndex.collect { case (e, pos) if pos % 2 == 0 => e }.toMap
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4, 5 -> 6)

You may also use sliding and foldLeft as follows:

scala> l.sliding(2,2).foldLeft(Map.empty[Int,Int]){ case (m, List(l, r)) => m + (l -> r) }
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4, 5 -> 6)


来源:https://stackoverflow.com/questions/24800432/how-to-convert-two-consecutive-elements-from-list-to-entries-in-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!