java Collections 对List进行排序

在java的项目中,list,map是使用相当频繁的工具类,有的时候在迭代map,将map中的对象添加到list中的时候,有可能会改变list中对象的顺序,我一般是循环list重新排序,其实在java中已经有过对list的一些常用方法的封装,就是Collections类,他有一个方法sort就是将list中的对象排序,前提是,list中的对象要实现Comparable<Object> 方法,然后覆盖compareTo方法,方法内容就是排序的规则。下面给出一个例子说明:

第一步:对象实现Comparable接口,并覆盖 compareTo比较方法

写道
public class SD_ShenshouLevelSkillPo implements Comparable<SD_ShenshouLevelSkillPo>

{
private int qunxiu_address_id;
private int shenshou_level;
private int skill_id;
private String shenshou_level_name;

public String getShenshou_level_name() {
return shenshou_level_name;
}
public void setShenshou_level_name(String shenshou_level_name) {
this.shenshou_level_name = shenshou_level_name;
}
public int getQunxiu_address_id() {
return qunxiu_address_id;
}
public void setQunxiu_address_id(int qunxiu_address_id) {
this.qunxiu_address_id = qunxiu_address_id;
}
public int getShenshou_level() {
return shenshou_level;
}
public void setShenshou_level(int shenshou_level) {
this.shenshou_level = shenshou_level;
}
public int getSkill_id() {
return skill_id;
}
public void setSkill_id(int skill_id) {
this.skill_id = skill_id;
}
@Override




public int compareTo



(SD_ShenshouLevelSkillPo o) {
if(getShenshou_level()>o.getShenshou_level()){
return 1;//返回1是往下排

}
if(getShenshou_level()<o.getShenshou_level()){
return -1;//返回-1是往上排
}
return 0;
}
} 






 第二步:用collections 为list中的对象排序

public List<SD_ShenshouLevelSkillPo> getByShenshou(int shenshouId){
	List<SD_ShenshouLevelSkillPo> list = new ArrayList<SD_ShenshouLevelSkillPo>();
	for(Iterator i = shenshouLevelSkillMap.keySet().iterator();i.hasNext();){
		SD_ShenshouLevelSkillPo po  = shenshouLevelSkillMap.get(i.next());
		if(po.getQunxiu_address_id() == shenshouId){
			list.add(po);
		}
	}
		Collections.sort(list);




		return list;
	}





你可能感兴趣的:(Collections)