java treeset 实 现 排 序&& 去 %%重%%

来源:互联网 发布:wifi网络连接不可用 编辑:程序博客网 时间:2024/05/30 04:29

1.例子要求:假设对数据表的int字段weight,int id(id为主键),实现weight相同,则比较id,且id按降序排列。,若weight,id均相同,则为同一对象,将实现去重效果。

也就是判断去重的条件是:weight,id都返回值为0;

1.数据表数据:



public class APP {
public static void main(String[] args) {
QueryRunner runner = DBCommon.getQueryRunner();
Map<String,Set<RelationRegex>> regMap=getRegInfoByDb( runner);
System.out.println("正则按权重排序,id倒序的规则=======");
for(String key:regMap.keySet()){
Set<RelationRegex> rrSet=regMap.get(key);
for(RelationRegex r:rrSet){
System.out.println(r.getId()+"==="+r.getWeight());
}
}
System.out.println("======================================");
}
/**
 * 
 * @param runner
 * @return
 */
public static Map<String,Set<RelationRegex>> getRegInfoByDb(QueryRunner runner){
String sql="select a.name,b.* from relation_name as a ,relation_regex as b where a.id=b.relation_name_id and a.valid_flg=1 and b.valid_flg=1  order by b.weight asc,id desc ";
Map<String,Set<RelationRegex>> rrBeanMap=new TreeMap<String,Set<RelationRegex>>();
List<Map<String,Object>> mapList=null;
  try {
  mapList=runner.query(sql, new MapListHandler());
  for(Map<String,Object> map:mapList){
 String name= map.get("name")==null?"":map.get("name").toString();
 RelationRegex rr=new RelationRegex();
 rr.setId(map.get("id")==null?0:(Integer)map.get("id"));
 rr.setRegex(map.get("regex")==null?"":map.get("regex").toString());
 rr.setRelationName(name);
 rr.setRelationNameId(map.get("relation_name_id")==null?"":map.get("relation_name_id").toString());
 rr.setDirection(map.get("direction")==null?0:(Integer)map.get("direction"));
 rr.setWeight(map.get("weight")==null?0:(Integer)map.get("weight"));
 rr.setCreateTime(map.get("create_time")==null?"":map.get("create_time").toString().replace(".0", ""));
 Set<RelationRegex> rSet= rrBeanMap.get(name);
 if(rSet==null||rSet.size()<1){
 rSet= new TreeSet<RelationRegex>();
 rSet.add(rr);
 }
 else{
 rSet.add(rr);
 }
 rrBeanMap.put(name, rSet);
  }

} catch (Exception e) {
 
// TODO Auto-generated catch block  
e.printStackTrace();  

}
  return rrBeanMap;
}

2.Java 重写的核心代码:

public int compareTo(RelationRegex o) {
// TODO Auto-generated method stub
if(this.getWeight()>o.getWeight()){
return 1;
}
if(this.getWeight()==o.getWeight()){
//权重相同的话,比较主键id,倒序排列
//return new Integer(this.getId()).compareTo(new Integer(o.getId()));

  if(this.getId()>o.getId()){
  return -1;
  
  }
  else if(this.getId()==o.getId()){
return 0;   
  }
  else{
  return 1;
  }
}
else{
return -1;
}

}

运行结果:

正则按权重排序,id倒序的规则=======
6===1
3===2
8===5
7===5
2===0
1===0

======================================

源代码参考网盘 java/

原创粉丝点击