public <K, V extends Number> Map<String, Double> sortMap(Map<String, Double> map) {
class MyMap<M, N> {
private M key;
private N value;
private M getKey() {
return key;
}
private void setKey(M key) {
this.key = key;
}
private N getValue() {
return value;
}
private void setValue(N value) {
this.value = value;
}
}
ArrayList<MyMap<String , Double>> list = new ArrayList<MyMap<String , Double>>();
for (Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
MyMap<String, Double> my = new MyMap<String, Double>();
String key = i.next();
my.setKey(key);
my.setValue(map.get(key));
list.add(my);
}
Collections.sort(list, new Comparator<MyMap<String, Double>>() {
public int compare(MyMap<String, Double> o1, MyMap<String, Double> o2) {
if(o1.getValue().equals(o2.getValue())) {
return o1.getKey().compareTo(o2.getKey());
}else{
return (int)(o1.getValue().doubleValue() - o2.getValue().doubleValue());
}
}
});
Map<String,Double> sortMap = new LinkedHashMap<String, Double>();
for(int i = 0, k = list.size(); i < k; i++) {
MyMap<String, Double> my = list.get(i);
sortMap.put(my.getKey(), my.getValue());
}
return sortMap;
}