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.
P.S. If anyone has a better solution to sort the hashmap, please let me know as well.
CodePudding user response:
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]]