按值排序hashmap

时间:2014-02-28 17:04:44

标签: java hashmap

我想对地图进行排序。我有字符串作为键,整数作为值。

示例:

key      value
"1,3"     40
"1,5"     20 
"2,5"     10
"2,10"    30


Output:
"2,5"     10
"1,5"     20
"2,10"    30
"1,3"     40

我尝试了以下代码,但它无效。你能帮帮我吗?

 treemap = treemap = new TreeMap<String, Integer>();
while((line = br.readLine()) !=null )
        {
            int sum=0;

              sum = //something
              String keys = xCordinate + "," + yCordinate; //getting it
              treemap.put(keys, sum);

        }
        testMap(treemap );
    }

    public static void testMap(Map <String,Integer> map)
    {
        for(Integer value1 : map.values())
        {
            String keys = map.get(value1).toString(); //error in this line
            System.out.println(keys + "  " + value1);
        }
    }

在这里,我在树形图中得到了完美的值。当我调试并看到时,键值和计数是完美的,但是当我进入循环时,第二行出现错误。

栈跟踪

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at java.lang.Integer.compareTo(Unknown Source)
    at java.util.TreeMap.getEntry(Unknown Source)
    at java.util.TreeMap.get(Unknown Source)
    at TestJavaServer.testMap(TestJavaServer.java:75)
    at TestJavaServer.readFromFile(TestJavaServer.java:68)
    at TestJavaServer.main(TestJavaServer.java:22)

3 个答案:

答案 0 :(得分:0)

假设Java,你可以像这样排序hashmap:

public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
   List mapKeys = new ArrayList(passedMap.keySet());
   List mapValues = new ArrayList(passedMap.values());
   Collections.sort(mapValues);
   Collections.sort(mapKeys);

   LinkedHashMap sortedMap = new LinkedHashMap();

  Iterator valueIt = mapValues.iterator();
  while (valueIt.hasNext()) {
   Object val = valueIt.next();
   Iterator keyIt = mapKeys.iterator();

   while (keyIt.hasNext()) {
       Object key = keyIt.next();
       String comp1 = passedMap.get(key).toString();
       String comp2 = val.toString();

       if (comp1.equals(comp2)){
           passedMap.remove(key);
           mapKeys.remove(key);
           sortedMap.put((String)key, (Double)val);
           break;
       }

   }

   }
  return sortedMap;

} 只是一个启动示例,这种方式更有用,因为它对HashMap进行排序并保留重复值。

答案 1 :(得分:0)

当您致电map.get(something)时,something必须与地图的(在您的情况下为String)的类型相同,但是您正在通过在Integer

答案 2 :(得分:0)

代码

public static void testMap(Map <String,Integer> map)

说你的地图有String类型的键,而这里

String keys = map.get(value1).toString(); //error in this line
                        --

value1是一个整数,因此是例外。