0

I had developed the below code in which we can sort the Hash Map basis on the key as well as on the basis of value also.

the main logic is that we can sort Map, be it HashMap or Hashtable by copying keys into List than sorting List by using Collections.sort() method, here you can use either Comparator or Comparable based upon whether you want to sort on custom order or natural order. Once List of keys are sorted, we can create another Map, particularly LinkedHashMap to insert keys in sorted order. LinkedHashMap will maintain the order on which keys are inserted, result is a sorted Map based on keys

My query is that if you cal please advise me for other better approach or any improvement you guys can suggest.

public class MapSortingExample {


    public static void main(String args[]) {

        //creating Hashtable for sorting
        Map<String, Integer> olympic2012 = new HashMap<String, Integer>();

        olympic2012.put("England", 3);
        olympic2012.put("USA", 1);
        olympic2012.put("China", 2);
        olympic2012.put("Russia", 4);
        //olympic2012.put("Australia", 4); //adding duplicate value

        //printing hashtable without sorting
        System.out.println("Unsorted Map in Java : " + olympic2012);

        //sorting Map e.g. HashMap, Hashtable by keys in Java
        Map<String, Integer> sorted = sortByKeys(olympic2012);
        System.out.println("Sorted Map in Java by key: " + sorted);


        //sorting Map like Hashtable and HashMap by values in Java
        sorted = sortByValues(olympic2012);
        System.out.println("Sorted Map in Java by values: " + sorted);


        //Sorting Map in Java by keys using TreeMap
        Map<String, Integer> sortedMapByKeys = new TreeMap<String,Integer>();
        sortedMapByKeys.putAll(olympic2012);
        System.out.println("Sorted Map in Java by key using TreeMap : " + sortedMapByKeys);


        //Sorting Map by keys in Java using Google Collections (Guava)
        //Main benefit is you can specify any ordering like natural or toString or arbitrary
        Map<String, Integer> sortingUsingGuava = Maps.newTreeMap(Ordering.natural());
        sortingUsingGuava.putAll(olympic2012);
        System.out.println("Example to sort Map in Java using Guava : " + sortingUsingGuava);



    }

    /*
     * Paramterized method to sort Map e.g. HashMap or Hashtable in Java
     * throw NullPointerException if Map contains null key
     */
    public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
        List<K> keys = new LinkedList<K>(map.keySet());
        Collections.sort(keys);

        //LinkedHashMap will keep the keys in the order they are inserted
        //which is currently sorted on natural ordering
        Map<K,V> sortedMap = new LinkedHashMap<K,V>();
        for(K key: keys){
            sortedMap.put(key, map.get(key));
        }

        return sortedMap;
    }

    /*
     * Java method to sort Map in Java by value e.g. HashMap or Hashtable
     * throw NullPointerException if Map contains null values
     * It also sort values even if they are duplicates
     */
    public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
        List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());

        Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {

            @Override
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });

        //LinkedHashMap will keep the keys in the order they are inserted
        //which is currently sorted on natural ordering
        Map<K,V> sortedMap = new LinkedHashMap<K,V>();

        for(Map.Entry<K,V> entry: entries){
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

}

output would be..

Unsorted Map in Java : {USA=1, England=3, Russia=4, China=2}
Sorted Map in Java by key: {China=2, England=3, Russia=4, USA=1}
Sorted Map in Java by values: {USA=1, China=2, England=3, Russia=4}
Sorted Map in Java by key using TreeMap : {China=2, England=3, Russia=4, USA=1}
Example to sort Map in Java using Guava : {China=2, England=3, Russia=4, USA=1}
alnasfire
  • 720
  • 6
  • 23
user2080568
  • 93
  • 1
  • 2
  • 8
  • Why aren't you using a `TreeMap`? It will keep your keys in sorted order. – Brigham Feb 19 '13 at 17:50
  • @Brigham I have shown th//Sorting Map in Java by keys using TreeMap Map sortedMapByKeys = new TreeMap(); sortedMapByKeys.putAll(olympic2012); System.out.println("Sorted Map in Java by key using TreeMap : " + sortedMapByKeys) – user2080568 Feb 19 '13 at 17:52
  • I think this question belongs to http://codereview.stackexchange.com/ – Luiggi Mendoza Feb 19 '13 at 18:04
  • So to be clear on what you're trying to do here, you want a process that takes a single `Map`, and results in two `Map`s, one sorted by key and one sorted by value? – sharakan Feb 19 '13 at 18:22

1 Answers1

2

A better approach is to use TreeMap with a given comparator instead of "manual" sorting and putting results into a LinkedHashMap

Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55