【问题标题】:How to sort data in Scala?如何在 Scala 中对数据进行排序?
【发布时间】:2019-10-27 20:09:15
【问题描述】:

我必须对列表中的数据进行排序,但我不知道如何。 我有一些代码:

mailClient.messages(unreadMessages)
      .flatMap(_.files)
      .filter(filename => {
        filename._1.contains("test") && filename._1.endsWith("csv")
      })
      .toList
      .sortWith((f, f1) => getFileDate(f._1).compareTo(getFileDate(f._1)))

这是我的下一个 getDate 函数:

def getFileDate(filename:String):LocalDate = {
    val fileParts = filename.split("_")
    val day = Integer.parseInt(fileParts(2))
    val month = Integer.parseInt(fileParts(3))
    val year = Integer.parseInt(fileParts(4))
    new LocalDate(year, month, day)
  }

我从我的文件名 (test_03_05_2019.csv) 中获取日期并尝试按此日期排序并收到此编译错误。


Error:(56, 14) No implicit Ordering defined for java.time.LocalDate.
      .sortBy(f => getFileDate(f._1))
Error:(56, 14) not enough arguments for method sortBy: (implicit ord: scala.math.Ordering[java.time.LocalDate])List[(String, String)].
Unspecified value parameter ord.
      .sortBy(f => getFileDate(f._1))
Error:(57, 99) type mismatch;
 found   : Any
 required: String
      .map { case (filename, csv) => Source.fromString(logger.trace(s"Csv $filename content: {}", csv)) }

我该怎么做?

【问题讨论】:

标签: scala


【解决方案1】:

您的java.time.LocalDate 似乎需要Ordering - 请参阅此answer

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

【讨论】:

    【解决方案2】:

    应该这样做。

    .sortWith(getFileDate(_._1) isBefore getFileDate(_._1))
    

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 1970-01-01
      • 2019-05-17
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多