Wednesday, February 10, 2010

HashMap Sorting

public LinkedHashMap sortHashMap(HashMap uMap) {
List mKey = new ArrayList(uMap.keySet());
List mValues = new ArrayList(uMap.values());
Collections.sort(mValues);
Collections.sort(mKey);

LinkedHashMap sortedMap =
new LinkedHashMap();

Iterator valueIt = mValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mKey.iterator();

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

if (comp1.equals(comp2)){
uMap.remove(key);
mKey.remove(key);
sortedMap.put((String)key, (String)val);
break;
}
}
}
return sortedMap;
}

Original Post Click here

1 comment:

Unknown said...

toronto translation services Thank you for sharing this article. I love it. Keep on writing this type of great stuff.