Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking. I'm 24, born in Romania, studied at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff.

Wednesday, December 21, 2011

Sorting a HashMap By Values Without Losing Duplicates

The below method sorts a HashMap by values without removing duplicates. It works for <String,String> but it can be modified accordingly for other types:

private LinkedHashMap sortMapByValuesWithDuplicates(Map passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());

LinkedHashMap sortedMap = new LinkedHashMap();

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

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

if (comp1.equals(comp2)) {
sortedMap.put((String) key, (String) val);
return sortedMap;

1 comment:

Christian Schlichtherle said...

See my comment on DZone: