HashMap中按key排序
阿新 • • 發佈:2019-01-25
今天面試,碰到一問題,覺得挺有意思的,記錄下來。
以下程式碼,print方法輸出的是key的集合:[1, 20, 3, 9],現在print2方法要實現以下功能,將map中的key-value按以下方式打印出來:
1----v1
3----v3
9----v9
20----v20
其中,map中的key是String型別的,但都是自然數,也即key為:"1" "2" "8" "10"這樣子的。請補充完print2方法
package test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class MapSortTest { private static void print(HashMap<String,String> k_v){ ArrayList<String> keyList = new ArrayList<String>(); keyList.addAll(k_v.keySet()); Collections.sort(keyList); System.out.println(keyList); } private static void print2(HashMap<String, String> k_v){ } public static void main(String[] args) { HashMap<String, String> k_v = new HashMap<String, String>(); k_v.put("1", "v1"); k_v.put("3", "v3"); k_v.put("20", "v20"); k_v.put("9", "v9"); print(k_v); print2(k_v); } }
分析:在集合中,有排序方法,Collections.sort(list,c),直接重寫Comparator介面的compare方法,就能實現print2的方法。完整程式碼如下
package test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class MapSortTest { private static void print(HashMap<String,String> k_v){ ArrayList<String> keyList = new ArrayList<String>(); keyList.addAll(k_v.keySet()); Collections.sort(keyList); System.out.println(keyList); } private static void print2(HashMap<String, String> k_v){ List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String, String>>(k_v.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, String>>() { @Override public int compare(Entry<String, String> o1, Entry<String, String> o2) { // 升序排序 return Integer.parseInt(o1.getKey())-Integer.parseInt(o2.getKey()); } }); for (Entry<String, String> entry : list) { System.out.println(entry.getKey()+"----"+entry.getValue()); } } public static void main(String[] args) { HashMap<String, String> k_v = new HashMap<String, String>(); k_v.put("1", "v1"); k_v.put("3", "v3"); k_v.put("20", "v20"); k_v.put("9", "v9"); print(k_v); print2(k_v); } }
輸出為:
[1, 20, 3, 9]
1----v1
3----v3
9----v9
20----v20