javarevisited |
How to sort HashMap by key and value in Java - Example Tutorial Posted: 19 Dec 2012 04:02 AM PST Sorting HashMap in Java is not as easy as it sounds because unfortunately Java API doesn't provide any utility method to sort HashMap based on keys and values. Sorting HashMap is not like sorting ArrayList or sorting Arrays in Java. If you are wondering why we can not use Collections.sort() method than for your information it only accepts List<E>, which leaves us to write our own utility methods to sort Map in Java. This is true for all types of Map like Hashtable, HashMap and LinkedHashMap. TreeMap is an already a sorted Map so we don't need to sort it again. Why we need to sort HashMap in Java, Why can't we use TreeMap in place of HashMap is the question appears in most Java programmer's mind when they asked to sort HashMap in Java. Well TreeMap is way slower than HashMap because it runs sorting operation with each insertion, update and removal and some time you don't really need an all time sorted Map, What you need is an ability to sort any Map implementation based upon its key and value. In last couple of articles we have seen How to loop or traverse Map in Java and in this Java tutorial we will see couple of ways to sort HashMap in Java. |
You are subscribed to email updates from Javarevisited To stop receiving these emails, you may unsubscribe now. | Email delivery powered by Google |
Google Inc., 20 West Kinzie, Chicago IL USA 60610 |
Post a Comment