2/16/11

Sorting HashMap with different Scenarios


This code snippet will explain the hashmap functionality and its sorting feature.

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());
        }
    }


    
}

No comments:

Post a Comment

Popular Posts