Wednesday, 25th April 2012
Follow WikiJava on twitter now. @Wikijava

Sort a HashMap

From WikiJava

Jump to: navigation, search


This example shows how to sort an HashMap in various ways

Contents

the article

Maps 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 keys

Map<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 values

Map<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 Map

Set<K> ref = map.keySet();
 
for (K obj : ref) {
}

See Also

Real's Java How To

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.