在Scala对象中按字符串格式按日期排序

时间:2018-05-07 13:46:52

标签: scala list sorting

我在scala(案例类)中有以下对象结构:

{
    "accounts": [{
        "accountManagement": {

            "accountStatus": "submitted",
            "accountManagementId": "1513684862218",
            "submittedDate": "19/12/2017"

        }
    }]
}

查看List" accounts"。我想根据字段" submittedDate"对此列表进行排序。来自" accountManagement"。请注意,提交的日期是字符串格式。

我试过这个但没有工作。

for (accountManagement: AccountManagement <- accountManagementList) {
        try {

          if(accountManagement.submittedDate != null && accountManagement.submittedDate.nonEmpty){

            accountManagement.submittedDate = dateFormatter.parse(accountManagement.submittedDate)
          }

        }catch {
          case e:Exception =>
        }

        accountManagementsNew = accountManagementsNew ::: List(accountManagement)
      }

      accountManagementsNew.sortBy(_.updatedDate.getTime)

2 个答案:

答案 0 :(得分:0)

让我们说你的案例类看起来像这样。

// Note that in scala its preferred to use Option to indicate nullable fields
case class AccountManagement(accountStatus: String,
                             accountManagementId: Long,
                             submittedDate: Option[String])

val accounts = List(
  AccountManagement("submitted", 1L, Some("21/12/2017")),
  AccountManagement("submitted", 2L, Some("19/12/2017")),
  AccountManagement("submitted", 3L, None),
  AccountManagement("submitted", 4L, Some("20/12/2017"))
)

val dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy")

您可以定义要在此上下文中使用的隐式排序

implicit val localDateOrdering: Ordering[LocalDate] = Ordering.by(_.toEpochDay)

accounts.filterNot(_.submittedDate.isEmpty) sortBy {
  case AccountManagement(_, _, Some(submittedDateString)) => LocalDate.parse(submittedDateString, dtf)
}

或者您可以直接指定您希望使用所述日期的毫秒表示来对数据集进行排序

accounts.filterNot(_.submittedDate.isEmpty) sortBy {
  case AccountManagement(_, _, Some(submittedDateString)) => LocalDate.parse(submittedDateString, dtf).toEpochDay
}

答案 1 :(得分:0)

如果我正确理解您的要求,您可以先将AccountManagementNew的{​​{1}}列表,将字符串类型的日期转换为AccountManagement,然后按日期按日期排序下面。请注意,LocalDate用于处理Try个案例。

Success/Failure