LoginSignup
8
9

More than 5 years have passed since last update.

Scala で Stream を使った日付シーケンスの取得

Last updated at Posted at 2014-07-23

システムの傾向調査、問題分析などを行っておりますと期間指定で集計処理を行うことがよくあります。期間の開始日から終了日まで Calendar#add() しながら while で回してもいいんですけど、Scala なら Stream を使えばソレっぽく書けます。

import java.util.{Calendar, Date}
def days(begin:Date):Stream[Date] = {
  val cal = Calendar.getInstance
  cal.setTime(begin)
  cal.add(Calendar.DAY_OF_MONTH, 1)
  begin #:: days(cal.getTime)
}

// from から to までの全ての日で処理を実行
val from:Date = ...
val to:Date = ...
days(from).takeWhile{ ! _.after(to) }.foreach{ date =>
  // ...
}

Stream の使用例を見ているとフィボナッチ数列的なものばかりなのでもう少し実用的な例としてメモしておきます。

8
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9