wipman
wipman

Reputation: 581

Sort files by name

How can I sort in ascending/descending order a group of files based on their name with the following naming convention: myPath\numberTheFileInt.ext?

I would like to obtain something like the following:

myPath\1.csv
myPath\02.csv
...
myPath\21.csv
...
myPath\101.csv

Here is what I have at the moment:

myFiles = getFiles(myFilesDirectory).sortWith(_.getName < _.getName)

Despite the files being sorted in the directory, they are unsorted in myFiles. I have in output:

myPath\1.csv
myPath\101.csv
myPath\02.csv
...
myPath\21.csv

I tried multiple things but it always throws an NoSuchElementException.

Has anyone already done this?

Upvotes: 0

Views: 1222

Answers (2)

JRomero
JRomero

Reputation: 4868

Comparing strings would yield an order based on unicode values of the strings being compared. What you need is to extract the file number and order based on that as an Integer.

import java.io.File

val extractor = "([\\d]+).csv$".r

val files = List(
  "myPath/1.csv",
  "myPath/101.csv",
  "myPath/02.csv",
  "myPath/21.csv",
  "myPath/33.csv"
).map(new File(_))


val sorted = files.sortWith {(l, r) =>
  val extractor(lFileNumber) = l.getName
  val extractor(rFileNumber) = r.getName

  lFileNumber.toInt < rFileNumber.toInt
}

sorted.foreach(println)

Results:

myPath/1.csv
myPath/02.csv
myPath/21.csv
myPath/33.csv
myPath/101.csv

UPDATE

An alternative as proposed by @dhg

val sorted = files.sortBy { f => f.getName match {
  case extractor(n) => n.toInt
}}

Upvotes: 1

dhg
dhg

Reputation: 52681

A cleaner version of J.Romero's answer, using sortBy:

val Extractor = "([\\d]+)\\.csv".r
val sorted = files.map(_.getName).sortBy{ case Extractor(n) => n.toInt }

Upvotes: 1

Related Questions