这次的场景是要对一个List<对象>中的某个属性进行自定义排序,废话不多说,直接上代码
首先你要自定义一个排序规则,比如下面这种
public class MySort {
public static final HashMap<String,Integer> SORTNAME= new HashMap<>(16);
static {
SORTNAME.put("老大",1);
SORTNAME.put("老二",2);
SORTNAME.put("老三",3);
SORTNAME.put("四弟",4);
SORTNAME.put("老五",5);
SORTNAME.put("老幺",6);
}
}
就是定义一个Map,然后将你要排序的属性值放进去,并规定好顺序
接下来就是最重要的一步了
public List<Object> sortList(List<Object> list){
Collections.sort(list, new Comparator<Object>()
{
@Override
public int compare(Object o1, Object o2) {
int i1 = MySort.SORTNAME.get((o1.getValue()));
int i2 = MySort.SORTNAME.get((o2.getValue()));
if (i1>i2){
return 1;
}else if (i1<i2){
return -1;
}else {
return 0;
}
}
});
return list;
}
到时候只需要掉用这个方法就可以得到一个排好序的List集合
其实就是重写一下Collections中的sort方法就可以了,应该还有很多其他的用法
有错误的地方欢迎各位大佬指正批评。