[英]convert List[String] into Map[String,String]
Anyone help me to convert list of strings into Map by indexes: (0,1) as key-value pair and index(2,3) as 2nd pair and index(3,4) as 3rd pair.任何人都可以帮助我通过索引将字符串列表转换为 Map:(0,1) 作为键值对,索引 (2,3) 作为第二对,索引 (3,4) 作为第三对。
Example: List("asd","fgh","qwe","tyu")
into Map("asd"->"fgh", "qwe"->"tyu")
例子:
List("asd","fgh","qwe","tyu")
into Map("asd"->"fgh", "qwe"->"tyu")
A simple matter of turning pairs into tuples and calling .toMap
on it. .toMap
转换为元组并在其上调用.toMap
简单问题。
val myMap = myList.grouped(2)
.collect{
case List(a,b) => (a,b)
case List(x) => (x,"")
}.toMap
Note: This doesn't check for duplicate keys so an input like List("a","b","a","c")
will result in Map("a" -> "c")
.注意:这不会检查重复键,因此像
List("a","b","a","c")
这样的输入将导致Map("a" -> "c")
。
This can be done using three standard library methods:这可以使用三种标准库方法来完成:
val list = List("asd","fgh","qwe","tyu")
list
.grouped(2) // Group elements in pairs
.map { // Convert pairs to tuples
case a :: b :: Nil => a -> b // Normal values to tuple
case a :: Nil => a -> "" // Final value if list size is odd
}
.toMap // Convert List[(A, B)] to Map[A,B]
Since you are creating a Map
, if the same even value appears more than once there will be duplicate keys, and only the final pair will be in the resulting Map
.由于您正在创建
Map
,如果相同的偶数值出现不止一次,则会出现重复的键,并且只有最后一对会出现在结果Map
。
(If you are new to Scala, the syntax a -> b
is another way of creating a tuple (a, b)
, and can be used in cases like this to make it clear that there is a key-value relationship between values in a pair) (如果您是 Scala 的新手,语法
a -> b
是另一种创建元组(a, b)
,并且可以在这样的情况下使用,以明确说明中的值之间存在键值关系一双)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.