1

This thread arises from my previous question. I need to create Seq[String] that contains paths as String elements, however now I also need to add numbers 7,8,...-22 after a date. Also I cannot use LocalDate as it was suggested in the answer to the above-cited question:

path/file_2017-May-1-7
path/file_2017-May-1-8
...
path/file_2017-May-1-22
path/file_2017-April-30-7
path/file_2017-April-30-8
...
path/file_2017-April-30-22
..

I am searching for a flexible solution. My current solution implies the manual definition of dates yyyy-MMM-dd. However it is not efficient if I need to include more than 2 dates, e.g. 10 or 100. Moreover filePathsList is currently Set[Seq[String]] and I don't know how to convert it into Seq[String].

val formatter = new SimpleDateFormat("yyyy-MMM-dd")
val currDay = Calendar.getInstance
currDay.add(Calendar.DATE, -1)
val day_1_ago = currDay.getTime
currDay.add(Calendar.DATE, -1)
val day_2_ago = currDay.getTime
val dates = Set(formatter.format(day_1_ago),formatter.format(day_2_ago))

val filePathsList = dates.map(date => {
  val list: Seq.empty[String]
  for (num <- 7 to 22) {
    list :+ s"path/file_$date-$num" + "
  }
  list
})
Community
  • 1
  • 1
user7379562
  • 349
  • 2
  • 6
  • 15
  • Set[Seq[String]] can easily be converted to Seq[String] via flatMap – Tanjin May 11 '17 at 21:02
  • @Tanjin: I finally did it using `.toSeq.flatten`, however the key question still remains - how to flexibly create such String elements for N dates. not just 2 as it shown in the code. – user7379562 May 11 '17 at 21:11

1 Answers1

3

Here is how I was able to achieve what you outlined, adjust the days val to configure the amount of days you care about:

import java.text.SimpleDateFormat
import java.util.Calendar

val currDay = Calendar.getInstance
val days = 5

val dates = currDay.getTime +: List.fill(days){
  currDay.add(Calendar.DATE, -1)
  currDay.getTime
}
val formatter = new SimpleDateFormat("yyyy-MMM-dd")
val filePathsList = for {
  date <- dates
  num <- 7 to 22
} yield s"path/file_${formatter.format(date)}-$num"
Tanjin
  • 2,442
  • 1
  • 13
  • 20
  • Great! It probably should be `val formatter = new SimpleDateFormat("yyyy-MMM-dd") val dates = currDay.getTime +: List.fill(days){ currDay.add(Calendar.DATE, -1) formatter.format(currDay.getTime) }` – user7379562 May 11 '17 at 21:55
  • Could you please explain what `yield` is doing? – user7379562 May 11 '17 at 21:55
  • I apologize for not using the formatter - I've updated the answer to reflect it's usage. This explains yield far better than I could: http://docs.scala-lang.org/tutorials/FAQ/yield.html – Tanjin May 11 '17 at 22:12