Android List数组列表自定义排序

自定义排序

例如:根据文件的最后修改时间进行排序,最新文件在前

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);
posted @ 2020-11-12 13:49  曲幽  阅读(3080)  评论(0编辑  收藏  举报