Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active December 15, 2015 20:59
Show Gist options
  • Save dacr/5322751 to your computer and use it in GitHub Desktop.
Save dacr/5322751 to your computer and use it in GitHub Desktop.
Looking for the shortest (1 line only) and cleanest way to extract a map from a collection of parameters
val args=Array("x=5", "y=10", "debug=true", "-verbose", "toto=truc1=titi", "nop", "tata=")
val argsRE="([^=]+)=(.*)".r
// ------- solution 1 with regex
args.flatMap{case argsRE(k,v) => Some(k->v) case _=> None}.toMap
// ------- solution 2 - with regex
args.collect{case argsRE(k,v) => k->v}.toMap
// ------- solution 3 - with regex
(for(argsRE(k,v) <- args) yield k->v).toMap
//------- solution 4 - with regex
args.flatMap(argsRE findFirstMatchIn _).map(x => x.group(1)->x.group(2)).toMap
//------- solution 5 - with split
args.map(_.split("=",2)).collect{case Array(k,v) => k->v}.toMap
//------- solution 6 - with split
(for(Array(k,v) <- args.map(_.split("=",2))) yield k->v).toMap
//------ solution 7 - with span
args.map(_.span(_!='=')).map{case (k,"")=>k->"" case (k,v)=>k->v.tail}.toMap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment