4 Replies Latest reply: Dec 19, 2007 8:26 AM by 807603 RSS

    Creating a sorted array from Keys in a HashMap

    807603
      I am trying to create an array which will hold the Keys of a hashMap but will be put in to an order which is dictated from the values of the hashmap.
      public class Persons{
      
           public static void main(String[] args)
           {
                Map map = new HashMap();
                List aList = new ArrayList();
                List bList = new ArrayList();
                Integer count = new Integer(0);
                
                map.put("Senior", "9");
                map.put("Master", "2");
                map.put("Apprentice", "4");
                map.put("Supervisor", "3");
                
                aList.addAll(map.values());
                Collections.sort(aList);
                Collections.reverse(aList);
                Iterator iterList = (aList.iterator());
                Iterator iterMap = (map.keySet()).iterator();
                
                //CODE TO USE THE SORTED LIST TO GET THE ASSOCIATED KEY.
                
                /*while(iterList.hasNext()) 
                {
                     if(iterList.next().equals(obj))
                }*/
      
                System.out.println(aList);
                System.out.println(map);
                System.out.println(bList);
           }
      }
      Output:
      [9, 4, 3, 2]
      {Senior=9, Apprentice=4, Master=2, Supervisor=3}
      []
      What i want to do is now create an array in which the keys are in the same positions as their values are in the first array
      so my final array output would be
      [Senior,Apprentice,Supervisor,Master]
      The actual contents of the hashmap will be dynamic so hard coding any of the actual transfers isn't possible. I have been pulling my hair out about this for quite some time and can just not seem to get my head around it.

      Edited by: Doombunny on Dec 19, 2007 5:02 AM