In Scala, how can I get the max date from an array of maps where one of the keys in the map is "date"? -


i have array of maps , maps , find maximum date in array of maps , think i'm heading down non-scala path because i'm not sure how wire pieces of question together.

is there better way of doing this? i'm concerned need assume things casting value date comparison, what's in map , map includes other data types (so map[string, object] have)

val df = new simpledateformat("yyyy-mm-dd")      def omap = list(map("date" -> df.parse("2013-08-01")), map("date" -> df.parse("2013-02-01"), "otherkey" -> "nothing special"), map("date" -> df.parse("2013-01-01"))) omap.max(new ordering[map[string, object]] {   def compare(x: map[string, object], y: map[string, object]) = x.get("date").get.asinstanceof[date] compareto y.get("date").get.asinstanceof[date] })  

the code seems work, feel i'm missing more scala way of doing this.

this little 1 liner works, throw exception if there no date in map:

omap.flatmap(map => map.get("date").collect({case d:date => d})).max 

here's safer version, have provide default date:

  val defaultdate = new date()   omap.map(map => map.get("date").collect({case d:date => d}))     .foldleft(defaultdate)((default, od) => od.fold(default)( d => if (d.compareto(default) > 0) d else default)) 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -