I have the following hashmap in java:
{B046=0.0, A061=3.0, A071=0.0, B085=0.0, B075=3.0, B076=9.0, B086=3.0, B095=0.0, B096=0.0, A052=0.0, B066=0.0, B056=9.0, B065=0.0, B055=9.0}
How should I go about sorting the hashmap such that the Alphabet, followed by the numerical figures are taken into account?
The resulting hashmap should look like this:
{A052=0.0,A061=3.0,A071=0.0,B046=0.0,B055=9.0,B056=9.0,B065=0.0,B066=0.0,B075=3.0,B076=9.0,B085=0.0,B086=3.0,B095=0.0,B096=0.0}
Appreciate the help!
HashMaps do not store the sorted order of keys by definition. You can however accomplish this by acquiring an array of the keys via: Object[] keys = map.
Step 1: Create a TreeMap in java with a custom comparator. Step 2: Comparator should compare based on values and then based on the keys. Step 3: Put all key-value pairs from the hashmap into the treemap. Step 4: return the treemap.
In order to sort in decreasing order, just reverse the order of Comparator using Collections. reverseOrder() or Comparator. reverse() method of Java 8.
Since LinkedHashMap guarantees insertion order of mappings, you will finally have a Map where contents are sorted by values. One difference between sorting HashMap by keys and values is that it can contain duplicate values by not duplicate keys. You cannot use TreeMap here because it only sorts entries by keys.
HashMap doesn't define the order of iteration over the elements. If you want to retrieve elements sorted by key use the TreeMap instead. However, since you store the strings in the format "DD/MM/YYYY" the order will likely be not the one you want, so either use the Date as a key or at least string of the form like "YYYY-MM-DD".
Remember, HashMap is not intended to keep entries in sorted order, so if you have a requirement to always keep entries in a particular order, don't use HashMap instead use TreeMap or LinkedHashMap .
Keys of a map are stored in a Set which can not be sorted. You can do it by adding the keys of the map set into a List and sorting that instead.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With