TreeMap比较器实现方式二(根据值与键结合起来排序)

1. 比较器实现
/**
 * TreeMap比较器(根据键值结合排序)
 *
 */
public class ByValueComparator  implements Comparator>>{
 private Map bankCodeMap = new HashMap();
 private Map valueMap = new HashMap();
 private int bankWeight = 0;
 private int B2BWeight = 0;
 
 
 public ByValueComparator(){
     bankCodeMap.put("ICBC", 1);
  bankCodeMap.put("CCB", 2);
  bankCodeMap.put("ABC", 3);
    }
   
 @Override
 public int compare(Entry> o1,
   Entry> o2) {
  Map value1 = o1.getValue();
  Map value2 = o2.getValue();
  
  if(olnyContainsB2B(value1) && olnyContainsB2B(value2)){
   
   return getB2BWeight(o1.getKey()) - getB2BWeight(o2.getKey());
  }else if(olnyContainsB2B(value1) || olnyContainsB2B(value2)){
   if(olnyContainsB2B(value1)){
    return 1;
   }else{
    return -1;
   }
  }else{
   return getBankWeight(o1.getKey()) - getBankWeight(o2.getKey());
  }
 }
 /**
  * 判断是否只包含B2B
  * @param map
  * @return
  */
 private boolean olnyContainsB2B(Map map){
  boolean flag = false;
  if(map ==  null){
   return flag;
  }
  if(map.size() == 1 && map.get("20") != null){
   flag = true;
  }
  return flag;
 }
 
 /**
  * 获取B2B权重
  * @param key
  * @return
  */
 private int getB2BWeight(String key){
  Integer value = valueMap.get(key);
  if(value == null){
   value = B2BWeight;
   valueMap.put(key, value);
   B2BWeight++;
  }
  return value;
 }
   
 /**
  * 获取银行代码权重
  * @param key
  * @return
  */
 private int getBankWeight(String key){
  Integer value = bankCodeMap.get(key);
  if(value == null){
   if(bankWeight == 0){
    bankWeight = Collections.max(bankCodeMap.values()) + 1;
   }else{
    bankWeight = bankWeight + 1;
   }
   
   value = bankWeight;
   bankCodeMap.put(key, value);
  }
  return value;
 }
}
2.测试代码
TreeMap> treeMap = new TreeMap>();
  Map map1 = new HashMap();
  map1.put("10", "B2C_map1");
  map1.put("20", "B2B_map1");
  
  Map map2 = new HashMap();
  map2.put("20", "B2B_map2");
  
  Map map3 = new HashMap();
  map3.put("20", "B2B_map3");
  
  Map map4 = new HashMap();
  map4.put("13", "Express_map4");
  
  treeMap.put("UOP", map1);
  treeMap.put("HP", map2);
  treeMap.put("ICBC", map3);
  treeMap.put("ABC", map4);
  treeMap.put("CCB", map1);
  treeMap.put("GDB", map3);
  
   ByValueComparator bvc  = new ByValueComparator();
         List>> newList=new ArrayList>>(treeMap.entrySet());
         Collections.sort(newList, bvc);
         for(Map.Entry> tempMap:newList){
          System.out.println(tempMap);
         }

你可能感兴趣的:(TreeMap比较器实现方式二(根据值与键结合起来排序))