Sort an array of files

From CodeCodex

Implementations[edit]

Java[edit]

Sort an array of File by modification date descending.

File f = new File(path); 

File [] files = f.listFiles(); 

Arrays.sort( files, new Comparator<File>()
{
	public int compare(File o1, File o2) {
		return o2.lastModified() - o1.lastModified();
	}

}); 

Source: BigBold

OCaml[edit]

Sort an array of files by last modification date from most recent to least recent. The following implementation executes the stat function only once per file for efficiency and correctness purposes:

# let sort a =
    let a' = Array.map (fun file -> (file, Unix.stat file)) a in
    Array.sort (fun (_, s1) (_, s2) ->
                  compare s2.Unix.st_mtime s1.Unix.st_mtime) a';
    Array.map fst a'
val sort : string array -> string array

We can use it to list the files of the current directory:

# sort (Sys.readdir Filename.current_dir_name);;
- : string array =
[| ... |]

Perl[edit]

<HIGHLIGHTSYNTAX language="perl"> sort {[stat $a]->[9] <=> [stat $b]->[9]} @list; # sort by mtime </HIGHLIGHTSYNTAX>

Ruby[edit]

Sort an array of File by modification date descending.

dirname = "/"
Dir.chdir(dirname) do
  array = Dir.entries('.').sort_by{|fname|File.mtime(fname)}.reverse
  array.each {|fname| puts "#{File.mtime(fname)} : #{fname}"}
end