java 根据不同属性,为对象排序
思路:
使用Comparator匿名内部类:
Collections.sort(list,new Comparator<road_info>() { @Override public int compare(road_info o1, road_info o2) { // TODO Auto-generated method stub return o2.getGreed_time()-o1.getGreed_time(); } });
碰到问题:
最近在练习一个android交通系统,其中有个模块需要根据用户需求,对各个路口的红绿灯市场进行排序,界面效果如下:
思考过程:
首先我想到了使用冒泡排序或者快速排序,但是因为业务逻辑需要多次排序,工作量太大所以放弃了,接着我先到了使用优先队列:将实体类实现Comparable接口,重写compareTo方法,具体代码如下:
public class road_info implements Comparable { String id; int red_time; int greed_time; int yellow_time; public road_info(String id,int red_time,int greed_time,int yellow_time){ this.id=id; this.red_time=red_time; this.greed_time=greed_time; this.yellow_time=yellow_time; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getRed_time() { return red_time; } public void setRed_time(int red_time) { this.red_time = red_time; } public int getGreed_time() { return greed_time; } public void setGreed_time(int greed_time) { this.greed_time = greed_time; } public int getYellow_time() { return yellow_time; } public void setYellow_time(int yellow_time) { this.yellow_time = yellow_time; } @Override public int compareTo(@NonNull Object o) { if(this.getGreed_time()< ((road_info) o).getGreed_time())return -1; else if(this.getGreed_time()> ((road_info) o).getGreed_time())return 0; if(this.getRed_time()< ((road_info) o).getRed_time())return -1; else if(this.getRed_time()> ((road_info) o).getRed_time())return 0; else return 1; } }
接着调用:Collections.sort(list);
但是这样只能根据对象的单个属性排序,但是不能根据其他属性排序,我上网查询资料找到了另外一种解决方案:使用Comparator匿名内部类实现
具体代码:
switch (i){ case 0: Collections.sort(list,new Comparator<road_info>() { @Override public int compare(road_info o1, road_info o2) { // TODO Auto-generated method stub return o1.getGreed_time()-o2.getGreed_time(); } }); break; case 1: Collections.sort(list,new Comparator<road_info>() { @Override public int compare(road_info o1, road_info o2) { // TODO Auto-generated method stub return o2.getGreed_time()-o1.getGreed_time(); } }); break; case 2: Collections.sort(list,new Comparator<road_info>() { @Override public int compare(road_info o1, road_info o2) { // TODO Auto-generated method stub return o1.getRed_time()-o2.getRed_time(); } });break; case 3: Collections.sort(list,new Comparator<road_info>() { @Override public int compare(road_info o1, road_info o2) { // TODO Auto-generated method stub return o2.getRed_time()-o1.getRed_time(); } });break; }
其实还可以实现Comparator接口,也同样可以实现这种效果,但是我没有深入了解,只能用这种本方法。如果有更好的算法,希望不吝赐教,谢谢。
到此,根据对象不同属性进行排序,已经解决了
参考资料:http://blog.****.net/wangtao****/article/details/71500500