Sort a HashMapFrom WikiJava
This example shows how to sort an HashMap in various ways
the articleMaps are collections of pairs key, value. They are useful in many occasions, in the Collections API they are considered as sets and thus they have no order. If you want to order the elements of an HashMap, below it's shown how to do that. sort based on the keysMap<K,V> yourMap= new HashMap<K,V>(); // put some tuples in yourMap ... Map<K,V> sortedMap = new TreeMap<K,V>(yourMap); Sort based on the valuesMap<K,V> yourMap = new HashMap<K,V>(); // put some tuples in yourMap ... // to hold the result Map<K,V> map = new LinkedHashMap<K,V>(); List<K> yourMapKeys = new ArrayList<K>(yourMap.keySet()); List<V> yourMapValues = new ArrayList<V>(yourMap.values()); TreeSet<V> sortedSet = new TreeSet<V>(yourMapValues); Object[] sortedArray = sortedSet.toArray(); int size = sortedArray.length; for (int i=0; i<size; i++) { map.put (yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]); } To iterate your new Sorted MapSet<K> ref = map.keySet(); for (K obj : ref) { } See Also |
