0

I have a list of files and I would like to group them according to the last modification date according to the year and month of change

I've tried to do something like:

val format = new SimpleDateFormat("yyyyMM")
files.groupBy(f=> format.format((f.lastModified())))

when files is a list of type File.

I'm doing this for fun...my goal is to be able to take all the files and place them in folders according to the year and date of last modification/creation(I've seen that not all OS has a files for the creation time and that is why I'm looking at the last modified)

boaz
  • 920
  • 1
  • 13
  • 32
  • 1
    [This answer](http://stackoverflow.com/a/32955978/1870803) does what you want. – Yuval Itzchakov Jan 25 '17 at 07:48
  • @YuvalItzchakov thank you for the answer. I was hoping to find a solution that uses the power of the functional part from Scala – boaz Jan 25 '17 at 07:57
  • What do you mean by *uses the power of functional part of Scala*? That's a single line of code containing a single lambda expression as the comparator. Looks pretty good to me :). – Yuval Itzchakov Jan 25 '17 at 07:59
  • The code in your question does what you are asking for. What exactly is missing? The last line evaluates to a map that maps from the formatted dates to lists of files. – lex82 Jan 25 '17 at 08:10
  • @lex82 -thank you for answering! maybe I'm missing something? how can I see the files by there group after the GroupBy? – boaz Jan 25 '17 at 08:44
  • `val grouped = files.groupBy(...); println(grouped);` should show you the resulting map in the console – lex82 Jan 25 '17 at 08:45

1 Answers1

1

The code you posted does exactly what you want. Just assign the result of the groupBy operation to some variable so you can work with it:

val grouped = files.groupBy(f=> format.format((f.lastModified())))

This gives you a Map[String,List[File]] assuming your files are in a list. The keys are your formatted dates (e.g. "201701") and the values the respective lists of files.

lex82
  • 11,173
  • 2
  • 44
  • 69