order HashMap

How to sort the values of a HashMap in Java and keep the duplicate entries

This is another way to sort a HashMap. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.

public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
    List mapKeys = new ArrayList(passedMap.keySet());
    List mapValues = new ArrayList(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);
        
    LinkedHashMap sortedMap = 
        new LinkedHashMap();
    
    Iterator valueIt = mapValues.iterator();
    while (valueIt.hasNext()) {
        Object val = valueIt.next();
        Iterator keyIt = mapKeys.iterator();
        
        while (keyIt.hasNext()) {
            Object key = keyIt.next();
            String comp1 = passedMap.get(key).toString();
            String comp2 = val.toString();
            
            if (comp1.equals(comp2)){
                passedMap.remove(key);
                mapKeys.remove(key);
                sortedMap.put((String)key, (Double)val);
                break;
            }

        }

    }
    return sortedMap;
}

How to sort the values of a HashMap in Java

If you want to sort a HashMap and keep the duplicate entries then see the solution in this article. Otherwise, read this article!

TASK
I want to sort my HashMap entries depending on the value of each one of them. I do not care about duplicate entries - duplicate entries are ignored by using this method. My HashMap is named as unSorted and it has values. In other words, it is defined as:

HashMap<String, Double> unSorted = new HashMap<String, Double>();

Now we put some sample entries in the HashMap, just to have something to order.

unSorted.put("Bristol", 23.45);
unSorted.put("London", 345.122);
unSorted.put("Manchester", 12.3);
unSorted.put("Edinburgh", 11.4);

Then we write a method that is able to take a HashMap as an input and after doing some crazy staff, it outputs the same HashMap but with its values sorted (ascending).

SOLUTION
This is the source code of the method:

private HashMap<String, Double> sortHashMap(HashMap<String, Double> input){
Map<String, Double> tempMap = new HashMap<String, Double>();
for (String wsState : input.keySet()){
tempMap.put(wsState,input.get(wsState));
}

List<String> mapKeys = new ArrayList<String>(tempMap.keySet());
List<Double> mapValues = new ArrayList<Double>(tempMap.values());
HashMap<String, Double> sortedMap = new LinkedHashMap<String, Double>();
TreeSet<Double> sortedSet = new TreeSet<Double>(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i=0; i<size; i++){
sortedMap.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),
(Double)sortedArray[i]);
}
return sortedMap;
}

Now, to retrieve a HashMap with sorted values, you just have to use(!) the method above.

HashMap<String, Double> sorted = new HashMap<String, Double>();
sorted = sortHashMap(unSorted);
Syndicate content