Sorting hashmap based on keys

Solution 1:

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.

Solution 2:

Use a TreeMap with a custom comparator.

class MyComparator implements Comparator<String>
    {
        public int compare(String o1,String o2)
        {
            // Your logic for comparing the key strings
        }
    }

TreeMap<String, Float> tm = new TreeMap<String , Float>(new MyComparator());

As you add new elements, they will be automatically sorted.

In your case, it might not even be necessary to implement a comparator because String ordering might be sufficient. But if you want to implement special cases, like lower case alphas appear before upper case, or treat the numbers a certain way, use the comparator.

Solution 3:

TreeMap is your best bet for these kind of sorting (Natural). TreeMap naturally sorts according to the keys.

HashMap does not preserve insertion order nor does it sort the map. LinkedHashMap keeps the insertion order but doesn't sort the map automatically. Only TreeMap in the Map interface sorts the map according to natural order (Numerals first, upper-case alphabet second, lower-case alphabet last).

Solution 4:

Use a TreeMap, although having a map "look like that" is a bit nebulous--you could also just sort the keys based on your criteria and iterate over the map, retrieving each object.

Solution 5:

Use TreeMap (Constructor):

Map<String, Float> sortedMap = new TreeMap<>(yourMap);

Use TreeMap (PutAll method):

Map<String, Float> sortedMap = new TreeMap<>();
sortedMap.putAll(yourMap);

Implementation of Map interface:

  1. TreeMap - Automatically sort the keys in ascending order while inserting.
  2. HashMap - Order of insertion won't be maintained.
  3. LinkedHashMap - Order of insertion will be maintained.