Sorting hashmap based on keys

JavaHashmap

Java Problem Overview


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!

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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 - Java

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.

Solution 6 - Java

Just use a TreeMap. It implements the SortedMap interface, and thus automatically sorts the keys it contains. Your keys can just be sorted alphabetically to get the desired result, so you don't even need to provide a comparator.

HashMaps are never sorted. The only thing you coulkd do with a HashMap is get all the keys, and store them in a sorted set or in a List and sort the List.

Solution 7 - Java

Using the TreeMap you can sort the Map.

Map<String, String> map = new HashMap<String, String>();        
Map<String, String> treeMap = new TreeMap<String, String>(map);
//show hashmap after the sort
for (String str : treeMap.keySet()) {
    System.out.println(str);
}

Solution 8 - Java

You can use TreeMap which will store values in sorted form.

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

Solution 9 - Java

TreeMap will automatically sort in ascending order. If you want to sort in descending order, use the following code:

Copy the below code within your class and outside of the main execute method:

static class DescOrder implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {	    
        return o2.compareTo(o1);
    }
    }

Then in your logic:

TreeMap<String, String> map = new TreeMap<String, String>(new DescOrder());
map.put("A", "test1");
map.put("C", "test3");
map.put("E", "test5");
map.put("B", "test2");
map.put("D", "test4");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1008697View Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavaKalView Answer on Stackoverflow
Solution 3 - JavaRoshnalView Answer on Stackoverflow
Solution 4 - JavaDave NewtonView Answer on Stackoverflow
Solution 5 - JavaSangeethView Answer on Stackoverflow
Solution 6 - JavaJB NizetView Answer on Stackoverflow
Solution 7 - JavaBERGUIGA Mohamed AmineView Answer on Stackoverflow
Solution 8 - JavaSaurabh PrajapatiView Answer on Stackoverflow
Solution 9 - JavaJavaGeekView Answer on Stackoverflow