java 对读取的文件进行排序

参数里面的isAscend 用来决定是升序排列 还是降序排列:


/***
* 按最后修改时间排序
* @param list
* @param isAscend
*/
public static void sortListByTime(List<FileInfo> list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorByTime comparator = new ComparatorByTime(isAscend);
if (!list.isEmpty()) {
Log.e("sortListByTime()", "");
synchronized (list) {
Collections.sort(list, comparator);
}

}
}
/**
* 按文件大小排序
* @param list
*/
public static void sortListBySize(List<FileInfo> list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorBySize comparator = new ComparatorBySize(isAscend);
if (!list.isEmpty()) {
Log.e("sortListBySize()", "");
synchronized (list) {
Collections.sort(list, comparator);
}

}
}
/**
* 按文件名称排序
* @param list
*/
public static void sortListByName(List<FileInfo> list , boolean isAscend) {
// 对ListView中数据list排序
ComparatorByName comparator = new ComparatorByName(isAscend);
if (!list.isEmpty()) {
Log.e("sortListByName()", "");
synchronized (list) {
Collections.sort(list, comparator);
}

}
}


补充上三个comparator:


public class ComparatorByName implements Comparator<FileInfo>{

boolean isAscend;
public ComparatorByName(boolean isAscend){
this.isAscend = isAscend;
}
public int compare(FileInfo f1, FileInfo f2) {

if(isAscend == true){
return Collator.getInstance(Locale.CHINESE).compare(f1.fileName, f2.fileName);
} else {
return Collator.getInstance(Locale.CHINESE).compare(f2.fileName, f1.fileName);
}

}

}


public class ComparatorBySize implements Comparator<FileInfo>{
boolean isAscend;
public ComparatorBySize(boolean isAscend){
this.isAscend = isAscend;
}
public int compare(FileInfo f1, FileInfo f2) {
long temp = new File(f2.filePath).length() - new File(f1.filePath).length();

if(isAscend == false){
if(temp > 0){
return 1;
}else if(temp == 0 ){
return 0;
}else{
return -1;
}
}else{
if(temp > 0){
return -1;
}else if(temp == 0 ){
return 0;
}else{
return 1;
}
}

}

}


public class ComparatorByTime implements Comparator<FileInfo>{


boolean isAscend;
public ComparatorByTime(boolean isAscend){
this.isAscend = isAscend;
}
public int compare(FileInfo f1, FileInfo f2) {
if(isAscend == false){
return f2.lastModifiedTime.compareTo(f1.lastModifiedTime);
} else {
return f1.lastModifiedTime.compareTo(f2.lastModifiedTime);
}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值