我有一個列表,我想將其分組,然後爲每個組獲得最大值。例如,用戶的動作列表,獲取每個用戶的最後一個動作。如何在Scala中使用MaxBy
case class UserActions(userId: String, actionId: String, actionTime: java.sql.Timestamp) extends Ordered[UserActions] {
def compare(that: UserActions) = this.actionTime.before(that.actionTime).compareTo(true)
}
val actions = List(UserActions("1","1",new java.sql.Timestamp(0L)),UserActions("1","1",new java.sql.Timestamp(1L)))
當我嘗試以下方法GROUPBY:
actions.groupBy(_.userId)
我收到一個地圖
scala.collection.immutable.Map[String,List[UserActions]] = Map(1 -> List(UserActions(1,1,1970-01-01 00:00:00.0), UserActions(1,1,1970-01-01 00:00:00.001))
這很好,但是當我嘗試添加maxBy我得到一個錯誤:
actions.groupBy(_.userId).maxBy(_._2)
<console>:13: error: diverging implicit expansion for type
Ordering[List[UserActions]]
starting with method $conforms in object Predef
actions.groupBy(_.userId).maxBy(_._2)
我應該改變什麼?
感謝 尼爾