Hi I am using following code to sort my HashMap, it sorts the map correctly but does not count the repeated values,
Map<String, Integer> mymap = new HashMap<String, Integer>();
mymap.put("item1", 5);
mymap.put("item2", 1);
mymap.put("item3", 7);
mymap.put("item4", 1);
Map<String, Integer> tempMap = new HashMap<String, Integer>();
for (String wsState : mymap.keySet()) {
tempMap.put(wsState, mymap.get(wsState));
}
List<String> mapKeys = new ArrayList<String>(tempMap.keySet());
List<Integer> mapValues = new ArrayList<Integer>(tempMap.values());
HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
TreeSet<Integer> sortedSet = new TreeSet<Integer>(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i = 0; i < size; i++) {
sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),
(Integer) sortedArray[i]);
}
for (Map.Entry<String, Integer> entry : mymap.entrySet())
System.out.println("Item is:" + entry.getKey() + " with value:"
+ entry.getValue());
System.out.println("***");
for (Map.Entry<String, Integer> entry : sortedMap.entrySet())
System.out.println("Item is:" + entry.getKey() + " with value:"
+ entry.getValue());
Result is as following (the item 4 is not shown because its value is same as item2's !!!) :
Item is:item4 with value:1
Item is:item2 with value:1
Item is:item3 with value:7
Item is:item1 with value:5
***
Item is:item2 with value:1
Item is:item1 with value:5
Item is:item3 with value:7
It is a HashMap and need to be sorted by value. Expected output is :
Item is:item3 with value:7
Item is:item1 with value:5
Item is:item2 with value:1
Item is:item4 with value:1
OR
Item is:item2 with value:1
Item is:item4 with value:1
Item is:item1 with value:5
Item is:item3 with value:7