Here you can find the source of sortHashMapByValues(HashMap passedMap, boolean ascending)
Parameter | Description |
---|---|
passedMap | a parameter |
ascending | a parameter |
public static LinkedHashMap sortHashMapByValues(HashMap passedMap, boolean ascending)
//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; } }