Java HashMap Sort sortHashMapByValues(HashMap passedMap, boolean ascending)

Here you can find the source of sortHashMapByValues(HashMap passedMap, boolean ascending)

Description

sort Hash Map By Values

License

LGPL

Parameter

Parameter Description
passedMap a parameter
ascending a parameter

Declaration

public static LinkedHashMap sortHashMapByValues(HashMap passedMap, boolean ascending) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.util.ArrayList;

import java.util.Collections;
import java.util.HashMap;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

public class Main {
    /**/* w w w  .  ja  v  a  2  s  .com*/
     * @param passedMap
     * @param ascending
     * @return
     */
    public static LinkedHashMap sortHashMapByValues(HashMap passedMap, boolean ascending) {

        List mapKeys = new ArrayList(passedMap.keySet());
        List mapValues = new ArrayList(passedMap.values());
        Collections.sort(mapValues);
        Collections.sort(mapKeys);

        if (!ascending)
            Collections.reverse(mapValues);

        LinkedHashMap someMap = new LinkedHashMap();
        Iterator valueIt = mapValues.iterator();
        while (valueIt.hasNext()) {
            Object val = valueIt.next();
            Iterator keyIt = mapKeys.iterator();
            while (keyIt.hasNext()) {
                Object key = keyIt.next();
                if (passedMap.get(key).toString().equals(val.toString())) {
                    passedMap.remove(key);
                    mapKeys.remove(key);
                    someMap.put(key, val);
                    break;
                }
            }
        }
        return someMap;
    }
}

Related

  1. sortByComparator(HashMap unsortMap, final boolean ascendingorder)
  2. sortByValue(HashMap map)
  3. sortedScoreMap(HashMap unSortedMap)
  4. sortHashMapByKeys(HashMap passedMap, boolean ascending)
  5. sortHashMapByValues( HashMap> passedMap, String key0)
  6. sortHashMapByValues(HashMap passedMap)
  7. sortMapByValue(HashMap map, final int sort)