1.对文件修改时间排序
/**
* 升序
*/
public void orderByTime(File[] fileList){
Arrays.sort(fileList, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = f1.lastModified() - f2.lastModified();
if (diff > 0)
return 1;
else if (diff == 0)
return 0;
else
//如果 if 中修改为 返回-1 同时此处修改为返回 1 排序就会是递减
return -1;
}
public boolean equals(Object obj) {
return true;
}
});
}
2.动态List分页(适用于对非数据库请求数据分页)
/**
* 分页
*
* @param list 传过来的集合
* @param currPage 页码
* @param pageSize 每页多少条数据
* @return 截取后的
*/
public static List<Message> startPage(List<Message> list, Integer currPage, Integer pageSize) {
if (list == null) {
return null;
}
if (list.size() == 0) {
return null;
}
//记录总数
Integer count = list.size();
//页数
Integer pageCount;
if (count % pageSize == 0) {
pageCount = count / pageSize;
} else {
pageCount = count / pageSize + 1;
}
//开始索引
int fromIndex;
//结束索引
int toIndex;
if (currPage > pageCount) {
currPage = pageCount;
}
if (!currPage.equals(pageCount)) {
fromIndex = (currPage - 1) * pageSize;
toIndex = fromIndex + pageSize;
} else {
fromIndex = (currPage - 1) * pageSize;
toIndex = count;
}
return list.subList(fromIndex, toIndex);
}
3.Map值排序
private Map<String, Integer> sortByValue(Map<String, Integer> map) {
// HashMap的entry放到List中
List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
// 对List按entry的value排序
list.sort(Map.Entry.comparingByValue());
// 将排序后的元素放到LinkedHashMap中
HashMap<String, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : list) {
temp.put(entry.getKey(), entry.getValue());
}
return temp;
}