java中map的两种遍历

public static void testEntry(){
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(1,"wangzhaotong");
    map.put(2,"huwenjing");
    map.put(3,"daidai");
    //第一种遍历map的方法++  Set<Map.Entry<Integer, String>> keys = map.entrySet();
    for(Map.Entry<Integer, String> k : keys){
        System.out.println(k.getKey()+ ":"+k.getValue());
    }
    //第二种遍历map的方法  Set<Integer> key = map.keySet();
    for(Integer integer  : key){
        System.out.println("map" + map.get(integer));
    }
    //重写Comparator方法
    List<Map.Entry<Integer, String>> list = new ArrayList<Map.Entry<Integer, String>>(map.entrySet());
    Collections.sort(list,new Comparator<Map.Entry<Integer, String>>(){
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2){
            return o1.getKey().toString().compareTo(o2.getKey().toString());
        }
    });
}

你可能感兴趣的:(java中map的两种遍历)