编程知识 cdmana.com

Android list array list custom sorting

Custom sort

for example : Sort the files according to their last modification time , The latest files are in front

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());
        // The default is positive order 
        return -Long.compare(f1.lastModified(), f2.lastModified());
    }
});

Custom data class sorting

Sort by file name

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 Internal comparison results :
                //ia > ib  return  1;ia < ib  return  -1;ia = ib  return  0
                return Integer.compare(ia, ib);
            }
            return 0;
        } else if (this.fileType.equals("Directory")) {
            return -1;
        } else return 1;
    }
}

Initializing custom arrays

ArrayList<FileListData> lstFiles = new ArrayList<FileListData>();

Call the sorting function of the list where sorting is needed , According to the above customized compareTo Sort

Collections.sort(lstFiles);

版权声明
本文为[Qu you]所创,转载请带上原文链接,感谢

Scroll to Top