Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert key values of Hashmap from String to int

I have this code snippet down below

public class hackkerankstuff {
    public static void countSort(List<List<String>> arr) {
        //taking the input List<List<String>> and storing it as a Hashmap
        HashMap<String, String> p = new HashMap<>();
        for (List<String> mapping : arr) {
            p.put(mapping.get(0), mapping.get(1));
        }
        //Converting data type of key to int
        Map<Integer, String> map2= new HashMap<>();
        for(Map.Entry<String, String> entry : p.entrySet())
            map2.put(entry.getKey().// No clue what to write here()//, entry.getValue());

that takes in a List<List<String>> which looks something like [['0','a']['3','d']['2','c']['1','a']] and I am storing them as a Hashmap, with x[0] as the key and x[1] as the values.

The second piece of code where I said //Converting data type of key to int, I am trying to sort the Hashmap by the key values, which range from 0 to any number given in the input. From my perspective, I would want to change the data type of the keys to an int first and then sort it by keys later on.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, this code wouldn’t even compile and I couldn’t figure out how to turn the key data values into an int. Any help on this would be greatly appreciated.

P.S. If anyone has a better solution to sort the hashmap, please let me know as well.

>Solution :

To solve your issue of conversion to an Integer you can simply use :

map2.put(Integer.parseInt(entry.getKey()), entry.getValue());

If anyone has a better solution to sort the hashmap, please let me
know as well.

I would simply use:

public static void countSort(List<List<String>> arr) {
    arr.sort(Comparator.comparingInt(v -> Integer.parseInt(v.get(0))));
}

Outputs

[[0, a], [1, a], [2, c], [3, d]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading