I'm trying to generate an infinite list of dates by substracting one month from the current date, i want to do this using Streams.
Here's what i've done so far :
import org.joda.time.LocalDate
var date = new LocalDate("2022-05-24")
val dateSeq = Seq(date)
val allDates = dateSeq.toStream Stream.continually(dateSeq)
.flatMap(ticks => ticks.map(_ => {
date = date.minusMonths(1)
date
}))
allDates.take(5).toList
My problem is that im using a var to decrement the current date by a month each time.
Is there any way to get rid of that var
?
CodePudding user response:
Using @Luis Miguel Mejía Suárez solution:
import org.joda.time.LocalDate
val numberOfMonthsBack = 5
val date = new LocalDate("2022-05-24")
val dateSeq = Seq(date)
val allDates = dateSeq.toStream Stream.continually(dateSeq)
.zip(Stream.from(1))
.flatMap(ticks =>
ticks._1.map(x => x.minusMonths(ticks._2))
)
allDates
.take(numberOfMonthsBack).toList
CodePudding user response:
You just want .iterate
rather than .continually
:
vall allDates = Stream.iterate(LocalDate.now) { _.minusMonth(1) }