这里采用的方法是:将要排序的类实现Comparable接口。具体如下:
① 假设有个rule类,要按照sort字段排序。首先该类要实现Comparable接口,并实现它的compareTo()方法。
/**
* @ Author:EvanChen
* @ Date:2018/9/17 17:02
* @ De ion:规则实体类
*/
public class Rule implements Comparable<Rule>{
/**
* @ De ion:规则id
* @ Version :1.0.0
*/
private Integer id;
/**
* @ De ion:规则名称
* @ Version :1.0.0
*/
private String name;
/**
* @ De ion:规则展示排序
* @ Version :1.0.0
*/
private Integer sort;
public Integer getId() {
return id;
}
public Rule setId(Integer id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Rule setName(String name) {
this.name = name;
return this;
}
public Integer getSort() {
return sort;
}
public Rule setSort(Integer sort) {
this.sort = sort;
return this;
}
@Override
public int compareTo(Rule o) {
return this.getSort().compareTo(o.getSort());
}
}
②使用时,只需调用 Collections.sort()方法即可,这里的rules是List<Rule>类型的。
Collections.sort(rules);
默认是升序,如需降序,则需要改一下上面的方法即可。
Collections.sort(rules, new Comparator<Rule>() {
public int compare(Rule o1, Rule o2) {
return o2.getSort() - o1.getSort();
}
);
继续阅读与本文标签相同的文章
下一篇 :
java随机生成字符串的方法(三种)
-
数字技术让“诗和远方”融为一体
2026-05-18栏目: 教程
-
“成人网站”免费让人上钩,其背后有什么不为人知的猫腻,网友:不敢惹
2026-05-18栏目: 教程
-
网络互连技术之路由协议
2026-05-18栏目: 教程
-
信息技术助力物流行业转型升级
2026-05-18栏目: 教程
-
登榜!风采依旧表现“佳”
2026-05-18栏目: 教程
