如何将HashMap的String类型键转为int并实现按键排序?
问题解决与优化方案
一、解决类型转换的编译问题
你需要用Integer.parseInt()方法将String类型的键转换为int,修改后的代码行如下:
map2.put(Integer.parseInt(entry.getKey()), entry.getValue());
二、更优的按键排序方案
HashMap本身是无序的,即使转换键类型后依然无法保证顺序,下面提供两种更合适的方案:
方案1:直接使用TreeMap(键唯一场景)
TreeMap会自动按照键的自然顺序(int的升序)排列,无需额外排序步骤。可以跳过中间的HashMap,直接将输入数据存入TreeMap:
public class hackkerankstuff { public static void countSort(List<List<String>> arr) { Map<Integer, String> sortedMap = new TreeMap<>(); for (List<String> mapping : arr) { int key = Integer.parseInt(mapping.get(0)); sortedMap.put(key, mapping.get(1)); } // 此时sortedMap已按键升序排列,可直接遍历使用 for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
注意:如果输入中有重复的键,TreeMap会保留最后一次存入的值,和HashMap行为一致。
方案2:列表排序(支持重复键场景)
如果输入存在重复键,需要保留所有条目,建议将数据存储为包含键值对的列表,再自定义排序规则:
import java.util.*; public class hackkerankstuff { public static void countSort(List<List<String>> arr) { // 将输入转换为包含Integer键和String值的列表 List<Map.Entry<Integer, String>> entryList = new ArrayList<>(); for (List<String> mapping : arr) { int key = Integer.parseInt(mapping.get(0)); entryList.add(new AbstractMap.SimpleEntry<>(key, mapping.get(1))); } // 按键升序排序 entryList.sort(Map.Entry.comparingByKey()); // 遍历输出结果 for (Map.Entry<Integer, String> entry : entryList) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
这种方式不会丢失任何条目,所有重复键的数据都会被保留并排序。
三、原代码的潜在问题
原代码中先存入HashMap<String, String>再转换类型,不仅多了一步冗余操作,还可能因为HashMap的无序性和键唯一性导致数据丢失或顺序混乱,建议直接使用上面的优化方案。
内容的提问来源于stack exchange,提问作者user18984687
相关产品推荐
相关产品推荐

