Home > Net >  Get list of all instants between 2 instants in Scala
Get list of all instants between 2 instants in Scala

Time:01-07

I want to get a list of all instants between today and (today - 15) days.

I am understanding I might need to you use LazyList if scala, but I am not so familiar with the syntax since I am new. The java equivalent seems to be

  Set <Instant> allPossibleDates =
    Stream.iterate(today, date -> date.minus(1, ChronoUnit.DAYS))
      .limit(numDates)
      .collect(Collectors.toSet());

What is the equivalent for this in Scala?

CodePudding user response:

The LazyList companion object defines an iterate method that lets you define a sequence in terms of a starting point and a step operation (Note: Iterator's companion defines a similar method):

def iterate[A](start: => A)(f: (A) => A): LazyList[A]

In fact it looks essentially the same as the Java version except that the start and f arguments appear in separate parameter lists. Pepper in Scala's syntax sugar for anonymous functions (using _ to represent the function argument), you can do

val today = Instant.now() // or whatever
LazyList
  .iterate(today) { _.minus(1, ChronoUnit.DAYS) }
  .take(15) // equivalent to `limit` in Java
  .to(Set) // equivalent to `collect(...)`

Also note that LazyList defines an overload of iterate which takes a limit, which would replace the .take:

LazyList
  .iterate(today, 15) { _.minus(1, ChronoUnit.DAYS) }
  .to(Set)

Note that you could do .foreach { instant => /* ... */ } instead of .to(SomeCollectionCompanion) to iterate the contents without allocating the memory for a collection.

  • Related