Friday, July 25, 2014

How to sort HashMap by key and value in Java Hashtable Map Example Tutorial

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, HashMapand 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 TreeMapis 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.
Read more »

Related Posts by Categories

0 comments:

 
Computer Blog - Powered By Blogger