---
title: "TreeMap比较器实现"
author: "zdk8105"
date: "2016-06-14T10:21:45Z"
tags: []
categories: ["编程语言"]
slug: "treemap"
draft: true
lastmod: "2016-06-14T10:25:10Z"
id: 2304822
url: "https://zdk8105.iteye.com/blog/2304822"
---

一、将TreeMap中指定元素排在集合前面

 

1\. 比较器实现

/\**  
 * TreeMap比较器  
 *  
 \*/  
public class MyComparator implements Comparator&lt;String&gt;{  
   
 private Map&lt;String,Integer&gt; bankCodeMap = new HashMap&lt;String,Integer&gt;();  
 private int tempWeight = 0;  
   
    public MyComparator(){  
       bankCodeMap.put("ICBC", 1);  
       bankCodeMap.put("CCB", 2);  
       bankCodeMap.put("ABC", 3);  
    }

 @Override  
 public int compare(String o1, String o2) {  
  int weight1 = getWeight(o1);  
  int weight2 = getWeight(o2);

  return weight1-weight2;  
 }

 /\**  
  * 获取权重  
  * @param key  
  * @return  
  \*/  
 private int getWeight(String key){  
  Integer value = bankCodeMap.get(key);  
  if(value == null){  
   if(tempWeight == 0){  
    tempWeight = Collections.max(bankCodeMap.values()) + 1;  
   }else{  
    tempWeight = tempWeight + 1;  
   }  
     
   value = tempWeight;  
   bankCodeMap.put(key, value);  
  }  
  return value;  
 }

}

2\. 测试代码

TreeMap&lt;String,String&gt; map = new TreeMap&lt;String,String&gt;(new MyComparator());  
  map.put("UOP", "STR1");  
  map.put("HP", "STR2");  
  map.put("ICBC", "STR3");  
  map.put("ABC", "STR4");  
  map.put("CCB", "STR5");  
  map.put("GDB", "STR6");  
    
  System.out.println(map);