自定義排序
例如:根據文件的最后修改時間進行排序,最新文件在前
Collections.sort(lstFiles, new Comparator<FileListData>() {
@Override
public int compare(FileListData fileListData, FileListData t1) {
File f1 = new File(fileListData.getFilePath());
File f2 = new File(t1.getFilePath());
//默認為正序
return -Long.compare(f1.lastModified(), f2.lastModified());
}
});
自定義數據類排序
根據文件名稱排序
public class FileListData implements Comparable<FileListData> {
private String fileName;
private String fileType;
public FileListData(String fileName, String fileType) {
this.fileName = fileName;
this.fileType = fileType;
}
public String getFileName() {
return this.fileName;
}
public String getFileType() {
return this.fileType;
}
@Override
public int compareTo(FileListData fileListData) {
if (this.fileType.equals(fileListData.getFileType())) {
int len = this.fileName.length();
if(fileListData.getFileName().length() < len) len = fileListData.getFileName().length();
for(int i = 0; i < len; i++){
int ia = (int) this.fileName.toUpperCase().charAt(i);
int ib = (int) fileListData.getFileName().toUpperCase().charAt(i);
if(ia == ib) continue;
//Integer.compare內部對比結果:
//ia > ib 返回 1;ia < ib 返回 -1;ia = ib 返回 0
return Integer.compare(ia, ib);
}
return 0;
} else if (this.fileType.equals("Directory")) {
return -1;
} else return 1;
}
}
初使化自定義數組
ArrayList<FileListData> lstFiles = new ArrayList<FileListData>();
在需要排序的地方調用列表的排序功能,按照上面自定義的 compareTo 進行排序
Collections.sort(lstFiles);
