日期:2014-05-20  浏览次数:20817 次

HashMap<Key,Value>如何按照value(Not Key)值的大小排序?
HashMap<integer,Double>如何按照value(Not Key)值的大小排序?
key和value 都市数值类型。
谢谢!
 

------解决方案--------------------
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class TagCounterSortTest
{
public static TreeMap < String,String > tagTreeMap = new TreeMap < String,String >();

public static void main(String[] args)
{
int initID = (int)(Math.random() * 12345);
for(int i = 0;i < 10;i++)
{
tagTreeMap.put(initID + "Tag" + i,"Tag" + i);
initID = (int)(Math.random() * 12345);
}
SortedMap sortMap = tagTreeMap.headMap(tagTreeMap.lastKey());
int tagSize = sortMap.size();
String[][] tagArray = new String[tagSize][2];
int index = 0;
Iterator it = sortMap.entrySet().iterator();
while(it.hasNext())
{
Map.Entry entry = (Map.Entry)it.next();
tagArray[index][0] = "" + entry.getValue();
tagArray[index++][1] = "" + entry.getKey();
//System.out.println(entry.getKey() + ":" + entry.getValue());
}
for(int i = tagSize - 1;i >= 0;i--)
{
//System.out.println(tagArray[i][0] + ":" + tagArray[i][1]);
}
//
Map < String,Map > map = new HashMap < String,Map >();
Map < String,Object > mapTagArray = new HashMap < String,Object >();
mapTagArray.put(SearchConstant.TAG_COUNTER,tagArray);
map.put(SearchConstant.TAG,mapTagArray);
//
Map mapTag = map.get(SearchConstant.TAG);
String[][] tagArrayList = (String [][])(mapTag.get("tagCounter"));
for(int i = tagArrayList.length - 1;i >= 0;i--)
{
System.out.println(tagArrayList[i][0] + ":" + tagArrayList[i][1]);
}
}
}
------解决方案--------------------
Java code

public class EntryComparator implments Comparator<Map.Entry<Integer, Double>> {
  public EntryComparator() {
  }

  public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2) {
    return o1.getValue().intValue() - o2.getValue().intValue();
  }
}

public class TestHashMapSort() {
  public static void outputSortedHashMap(HashMap<Integer, Double> map) {
    List<Map.Entry<Integer, Double>> list = new ArrayList<Map.Entry<Integer, Double>>(map.entrySet());
    Collections.sort(list, new EntryComparator());
    
    Iterator<Map.Entry<Integer, Double>> i = list.iterator();
    while (i.hasNext()) {
      Map.Entry<Integer, Double> entry = i.next();
      System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
    }
  }

  public static void main(String[] args) {
    HashMap<Integer, Double> map = new HashMap<Integer, Double>();
    // ... create you map here...
    outputSortedHashMap(map);
  }
}