Sort files that match a pattern

Hello,
I am trying to get the latest file from a list of files that match a regex pattern in Groovy.

I have found a piece of code that filter only the files that match a regex :

  Pattern pattern = Pattern.compile(myRegex)
  List<File> paths = Files.list(downloadsFolder)
  		.filter({ p -> Files.isRegularFile(p) })
  		.filter({ p -> pattern.matcher(p.getFileName().toString()).matches()})
  		.collect(Collectors.toList())

But this returns an unsorted List of File. I want the latest created file, and its path. I’m not sure how to do it in Groovy. Do you know how ? Thanks in advance.

All you want to know is how to sort an ArrayList().

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.stream.Collectors

Path downloadsFolder = Paths.get(System.getProperty("user.home")).resolve("Downloads")
List<File> paths = Files.list(downloadsFolder)
		.filter({ Path p -> Files.isRegularFile(p) })
		.collect(Collectors.toList())
		.sort({ Path p -> p.getFileName() })
		
paths.forEach({p ->
	println p
})

Hello,
Thanks for your answer but that’s not exactly what I’m looking for.

I want to sort the files so that I get the latest created as the first element of the list. Not just basing on its name. I know it’s feasible in Java, but in Groovy I haven’t found how to yet.

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.stream.Collectors

Path downloadsFolder = Paths.get(System.getProperty("user.home")).resolve("Downloads")
List<File> paths = Files.list(downloadsFolder)
		.filter({ Path p -> Files.isRegularFile(p) })
		.collect(Collectors.toList())
		.sort({ Path p -> Files.getLastModifiedTime(p) })
		.reverse()
		
paths.forEach({ Path p ->
	println "${Files.getLastModifiedTime(p)}\t${p}"
})