Wednesday 6 March 2019

How to sort hashmap? sorting with collections? Hashmap sorting with key?

This is a common interview question asked in most of the companies for people with 3+ years of experience in Automation:

public class hashmapsort {

    public static void main(String[] args) {

         HashMap<Integer, String> hmap = new HashMap<Integer, String>();
         hmap.put(1, "Java");
         hmap.put(13, "C");
         hmap.put(2, "Python");
         Map<Integer, String> map = new TreeMap<Integer, String>(hmap);
         System.out.println(" Sorting:");
         Set set2 = map.entrySet();
         Iterator iterator2 = set2.iterator();
         while(iterator2.hasNext()) {
              Map.Entry m2 = (Map.Entry)iterator2.next();
              System.out.print(m2.getKey() + ": ");
              System.out.println(m2.getValue());
         }
    }
}


Note: To sort with values need to do using comparator, will do that in my next post.

No comments:

Post a Comment

All Time Popular Posts

Most Featured Post

API Status Codes with examples for QA-Testers

  🔺 LinkedIn: https://www.linkedin.com/in/sidharth-shukla-77b53145/ 🔺 Telegram Group:  https://t.me/+FTf_NPb--GQ2ODhl 🏮In API testing, it...