简体   繁体   中英

beginner scala pattern matching - split a#b by # and assign to Map

I want to write some scala code that does the following:-

Converts a list of ["a#b","c#"] to a map with the portion before # as key and the portion after # as the value if the value exists.

So, for the above array the map would be:

{
 "a" => "b" // no "c" because it does not have a value.
}

What is the most elegant way to express this in scala style? Also, how are null checks performed in scala?

Thanks!

scala> val list = List("a#b", "c", "d#e", "")

scala> list.map(x => x.split("#")).filter(_.size == 2).map(arr => (arr(0), arr(1))).toMap
res1: scala.collection.immutable.Map[String,String] = Map(a -> b, d -> e) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM