Home > front end >  How can we sort a list in alphanumeric way in scala
How can we sort a list in alphanumeric way in scala

Time:03-19

I have a list ["img10", "img2", "img4", ...], I want to sort it and get ["Img1", "Img2", "Img3",...]. Using sorted the result is ["img1", "img10", "img100", ...]

CodePudding user response:

Assuming that you can have only names matching names like IMG_1111.JPG, or regex \D*\d*\.\w , it is possible to sort the sequence with the help of capturing regex groups and then prefixing numbers with a leading space .

import scala.jdk.StreamConverters._

val ImageNumberExt = raw"(\D*)(\d{1,10})\.(\w*)".r
Files
  .list(Path.of("/path/to/folder"))
  .toScala(LazyList)
  .map(_.toFile)
  .sortBy { f =>
    f.getName match {
      case ImageNumberExt(stringPrefix, number, ext) =>
        stringPrefix   f"$numbers"   ext
      case str =>
        str
    }
  }
  .foreach(println)

CodePudding user response:

Given that all files should have the same prefix and then they will have a numeric part, the best to do is to sort based on that numeric part like this:

import java.io.File

val files: List[File] = ...

val filesSorted =
  files.sortBy { file =>
    // Tune as needed.
    file.getName.trim.toLowerCase.stripPrefix(prefix = "img").toIntOption
  }
  • Related