9/3/10

Sorting HashMap based on key and also using Value

HashMap in java can be sorted using its key or value. Lets see an example.


package learningscenarios;


/**
 *
 * @author Raghu
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;


public class SortingHash {


    static Map myMap = new HashMap();
    static HashMap map = new LinkedHashMap();


    /**
     * setting values for hashmap
     */
    static void sethash() {
        myMap.put("E", 5);
        myMap.put("B", 2);
        myMap.put("A", 1);
        myMap.put("D", 4);
        myMap.put("C", 3);


    }
  
    public static void main(String a[]) {
        sethash();
        sortKey();
        sortValue();
    }


    /**
     * Sorting hashmap with key
     */
    static void sortKey() {
        SortedSet<String> sortedset = new TreeSet<String>(myMap.keySet());


        Iterator<String> it = sortedset.iterator();


        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }


    /**
     * Sorting hashmap with value
     */
    static void sortValue() {
        List yourMapKeys = new ArrayList(myMap.keySet());
        List yourMapValues = new ArrayList(myMap.values());
        TreeSet sortedSet = new TreeSet(yourMapValues);
        Object[] sortedArray = sortedSet.toArray();
        int size = sortedArray.length;
        System.out.println("---------------");
        for (int i = 0; i < size; i++) {
            System.out.println((Integer) sortedArray[i]);
        }
        for (int i = 0; i < size; i++) {
            map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])),
                    sortedArray[i]);
        }
        Set ref = map.keySet();
        Iterator it = ref.iterator();
        System.out.println("---------------");
        while (it.hasNext()) {


            System.out.println((String) it.next());
        }
    }


  
}

2 comments:

  1. This code but it needs to be udpated to use Generics. Here is an example of How to sort HashMap in Java by keys and values which uses generics

    ReplyDelete
  2. This code but it needs to be udpated to use Generics. Here is an example of How to sort HashMap in Java by keys and values which uses generics

    ReplyDelete

Popular Posts