Ashwini
Ashwini

Reputation: 900

Sorting Seq[scala.collection.immutable.Map[String,org.joda.time.DateTime]]

I have Seq of Map in scala, which is from hive partitions.

I need to get latest/recentbusinessdate from the below Seq of Map

import org.joda.time.DateTime

val a = Seq(
 Map("businessdate" -> DateTime.parse("2018-03-23T00:00:00.000Z")),
 Map("businessdate" -> DateTime.parse("2018-03-24T00:00:00.000Z")),
 Map("businessdate" -> DateTime.parse("2018-03-22T00:00:00.000Z")),
 Map("businessdate" -> DateTime.parse("2018-03-21T00:00:00.000Z"))
)

expected output is Map with recent business date. i.e.

Map("businessdate" -> DateTime.parse("2018-03-24T00:00:00.000Z")

I tried to sort this seq of map using sortWith but ended up with wrong results

val b = a.map(x => new DateTime( x.get("businessdate").get)
  .isAfter(new DateTime( x.get("businessdate").get)))
println(b)

I am new to scala. Any help is appreciated.

Upvotes: 1

Views: 262

Answers (1)

Mik378
Mik378

Reputation: 22191

Using sortWith to get the most recent Business Date:

val mapWithMostRecentBusinessDate = a.sortWith(
  (a, b) => a("businessdate").isAfter(b("businessdate"))
).head

println(mapWithMostRecentBusinessDate) 

Output: Map(businessdate -> 2018-03-24T00:00:00.000Z)

Another way using foldLeft, likely more performant than sorting the whole Seq since O(n):

val mapWithMostRecentBusinessDate = a.foldLeft(a.head)(
  (acc, b) =>
    if (b("businessdate").isAfter(acc("businessdate")))
      b
    else
      acc
)

println(mapWithMostRecentBusinessDate)

Output: Map(businessdate -> 2018-03-24T00:00:00.000Z)

Upvotes: 2

Related Questions