New to Scala, better/idiomatic way than reduceLeft to find max (key,val) in collection? -


new-ish scala ... trying find best match collection of (key,value) pairs, best match defined highest frequency. method reduceleft ideal, collection size may smaller 2 (1 or 0), well-defined behavior small collections good.

is there more idiomatic scala approach finding max? other sources explained reduceleft, makes sense , reads well, other approaches suggest different methods.

is there better way extract lone item collection of size=1?

assume have map unknown number of values, m:map[string,int]

val vm = m.filternot{ case (k,v) => k.equals("ignore") } val size = vm.size  val best = if(size>1) {   val list = vm.map{ case (k,v) => keycount(k,v) }   list.reduceleft( maxkey ) } else if(size == 1) {   vm.tolist(0)   //another source has suggested vm.head alternative } else {   keycount("default",0) } 

where keycount , maxkey declared as,

case class keycount( key:string, count:long ) {   def max( a:keycount, z:keycount ) = { if( a.count>z.count) else z; }   def min( a:keycount, d2:keycount ) = { if( a.count<z.count) else z; } }  val maxkey = (x:keycount, y:keycount) => if( x.count > y.count ) x else y; 

reduceleft works fine lists of size 1. if count greater 0 can use foldleft default case:

val list = vm.map{ case (k,v) => keycount(k,v) } val best = list.foldleft(keycount("default",0))(maxkey) 

otherwise use condition maxby or reduceleft:

val best = if(size>0) {   val list = vm.map{ case (k,v) => keycount(k,v) }   list.maxby(_.count) } else {   keycount("default",0) } 

note can use maxby on original map[string, int], there no need convert elements keycount.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -