I want to sort the map. I have string as key and integer as value.
Example:
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
I tried the below code but it is not working. Can you please help me out.
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);
}
}
Here, I get the perfect values in treemap..When I debug and see, the key value and count are perfect, but when i go in for loop, theere comes an error in second line.
StackTrace
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)