Last active
December 15, 2015 20:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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