I want to convert Seq keys / values to Map. The first element of the sequence is reserved, so the list of pairs starts at position 1 .
The question arises: is it possible to implement this function in a more functional way?
def list2Map(plainMap:Seq[String]) = {
var map = Map[String, String]()
var idx = 1;
while(plainMap.size > idx) {
val key = plainMap(idx)
idx += 1
val value = plainMap(idx)
idx += 1
map = map + (key -> value)
}
map
}
assert( list2Map( Seq("reserved slot","key0","value0","key1","value1","key2","value2") ) == Map( ("key0"->"value0"),("key1"->"value1"),("key2"->"value2") ) )
I am new to Scala and I know that there are many different ways to iterate through a collection, but I have not found a forEach way to read two elements to iterate starting from element 1.
PS: Thanks guys. I learn a lot with all the answers!
source
share