ComparisonChain-文件名排序

2022-06-28 19:21:32 浏览数 (1)

实现Comparable接口

代码语言:javascript复制
@Getter
@Setter
@Builder
@ToString
public class MyFile implements Comparable<MyFile> {
    public Integer id;
    private String name;

    @Override
    public int compareTo(MyFile other) {
        //return this.id-other.id;
        return ComparisonChain.start()
                .compare(this.id,other.id)
                .compare(this.name,other.name)
                .result();
    }
}

遍历指定文件夹,并按照自定义规则排序

代码语言:javascript复制
public class App {
    public static void main(String[] args) {
        File dir=new File("C:\Users\lenovo\Desktop\尚学堂Vue2.0");
        File[] files=dir.listFiles();
        List<MyFile> myFileList=new LinkedList<>();
        if(files!=null){
            for(File tmp:files){
                if (!tmp.isFile()){continue;}
                myFileList.add(MyFile.builder()
                        .id(Integer.valueOf(tmp.getName().substring(19,21).trim()))
                        .name(tmp.getName().substring(21).trim())
                        .build());               
            }
            myFileList.sort(MyFile::compareTo);
            Iterator iterator=myFileList.iterator();
            while (iterator.hasNext()){
                System.out.println(iterator.next());
            }
        }
    }
}

Post Views: 343

0 人点赞