我在Scala中有Map Seq,它来自蜂巢分区。
我需要从下面的地图序列中获取最新/最近的业务日期
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"))
)
预期输出为带有最近营业日期的地图。即
Map("businessdate" -> DateTime.parse("2018-03-24T00:00:00.000Z")
我尝试使用来排序此序列的地图,sortWith
但结果错误
val b = a.map(x => new DateTime( x.get("businessdate").get)
.isAfter(new DateTime( x.get("businessdate").get)))
println(b)
我是scala的新手。任何帮助表示赞赏。
使用sortWith
以获得最新的业务日期:
val mapWithMostRecentBusinessDate = a.sortWith(
(a, b) => a("businessdate").isAfter(b("businessdate"))
).head
println(mapWithMostRecentBusinessDate)
输出:Map(businessdate -> 2018-03-24T00:00:00.000Z)
使用O的另一种方法foldLeft
,Seq
因为O(n)可能比对整体排序更有效:
val mapWithMostRecentBusinessDate = a.foldLeft(a.head)(
(acc, b) =>
if (b("businessdate").isAfter(acc("businessdate")))
b
else
acc
)
println(mapWithMostRecentBusinessDate)
输出:Map(businessdate -> 2018-03-24T00:00:00.000Z)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句