Scala日期和按周分组

时间:2016-02-04 10:01:21

标签: scala

import java.time.LocalDate

case class Day(date: LocalDate, other: String)

val list = Seq(
  Day(LocalDate.of(2016, 2, 1), "text"),
  Day(LocalDate.of(2016, 2, 2), "text"),  // Tuesday
  Day(LocalDate.of(2016, 2, 3), "text"),
  Day(LocalDate.of(2016, 2, 4), "text"),
  Day(LocalDate.of(2016, 2, 5), "text"),
  Day(LocalDate.of(2016, 2, 6), "text"),
  Day(LocalDate.of(2016, 2, 7), "text"),
  Day(LocalDate.of(2016, 2, 8), "text"),
  Day(LocalDate.of(2016, 2, 9), "text"),
  Day(LocalDate.of(2016, 2, 10), "text"),
  Day(LocalDate.of(2016, 2, 11), "text"),
  Day(LocalDate.of(2016, 2, 12), "text"),
  Day(LocalDate.of(2016, 2, 13), "text"),
  Day(LocalDate.of(2016, 2, 14), "text"),
  Day(LocalDate.of(2016, 2, 15), "text"),
  Day(LocalDate.of(2016, 2, 16), "text"),
  Day(LocalDate.of(2016, 2, 17), "text")
)

// hard code, for example Tuesday
def groupDaysBy(list: Seq[Day]): List[List[Day]] = {
  ???
}

val result =
Seq(
  Seq(Day(LocalDate.of(2016, 2, 1), "text")),  // Separate
  Seq(Day(LocalDate.of(2016, 2, 2), "text"),  // Tuesday
    Day(LocalDate.of(2016, 2, 3), "text"),
    Day(LocalDate.of(2016, 2, 4), "text"),
    Day(LocalDate.of(2016, 2, 5), "text"),
    Day(LocalDate.of(2016, 2, 6), "text"),
    Day(LocalDate.of(2016, 2, 7), "text"),
    Day(LocalDate.of(2016, 2, 8), "text")),
  Seq(Day(LocalDate.of(2016, 2, 9), "text"),  // Tuesday
    Day(LocalDate.of(2016, 2, 10), "text"),
    Day(LocalDate.of(2016, 2, 11), "text"),
    Day(LocalDate.of(2016, 2, 12), "text"),
    Day(LocalDate.of(2016, 2, 13), "text"),
    Day(LocalDate.of(2016, 2, 14), "text"),
    Day(LocalDate.of(2016, 2, 15), "text")),
  Seq(Day(LocalDate.of(2016, 2, 16), "text"), // Tuesday
    Day(LocalDate.of(2016, 2, 17), "text"))
)

assert(groupDaysBy(list) == result)

我有一个Day对象列表,我希望每隔7天组合一次,开始日期可以是任何一天(从星期一到星期日,我以星期二为例)。

以上是我的要求的功能和预期结果。我想知道如何利用Scala集合API实现无尾递归?

2 个答案:

答案 0 :(得分:1)

以下是您可以做的事情:

// hard code, for example Tuesday
def groupDaysBy(list: Seq[Day]): Seq[Seq[Day]] = {
  val (list1,list2)= list.span(_.date.getDayOfWeek != DayOfWeek.TUESDAY)
  Seq(list1) ++ list2.grouped(7)
}

我建议将day作为参数而不是硬编码,因此它变为

// hard code, for example Tuesday
def groupDaysBy(list: Seq[Day], dayOfWeek: DayOfWeek): Seq[Seq[Day]] = {
  val (list1,list2)= list.span(_.date.getDayOfWeek != dayOfWeek)
  Seq(list1) ++ list2.grouped(7)
}

...

assert(groupDaysBy(list, DayOfWeek.TUESDAY) == result)

答案 1 :(得分:0)

映射列表以创建元组(GroupKey,value),其中GroupKey表示例如uniq周(年* 53 + week_of_the_year)的值。然后你可以分组GroupKey