简体   繁体   中英

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM