Map<String, Integer>遍历

public static void main(String[] args) {
 Map<String, Integer> map = new HashMap<String, Integer>();
          map.put("jack", 1);
          map.put("tom", 2);
          map.put("jerry", 3);
          // map遍历-for-each与keySet
          forKeySetTravelse(map);
          // map遍历-迭代器与keySet
          iteratorKeySetTravelse(map);
          // map遍历-for-each与entry
          forEntryTravelse(map);
          // map遍历-迭代器与entry
          iteratorEntryTravelse(map);
}

 

// map遍历-for-each与keySet
     private static void forKeySetTravelse(Map<String, Integer> map) {
          Set<String> set = map.keySet();
         for (String key : set) {
             Integer value = map.get(key);
            System.out.print(key + ":" + value + " ");
        }
         System.out.println();
    }

     // map遍历-迭代器与keySet
    private static void iteratorKeySetTravelse(Map<String, Integer> map) {
         Set<String> set = map.keySet();
         Iterator<String> it = set.iterator();
        while(it.hasNext()) {
            String key = it.next();
            Integer value = map.get(key);
             System.out.print(key + ":" + value + " ");
        }
         System.out.println();
     }
   
    // map遍历-for-each与entry
    private static void forEntryTravelse(Map<String, Integer> map) {
        Set<Entry<String, Integer>> set = map.entrySet();
        for (Map.Entry<String, Integer> entry : set) {
            String key = entry.getKey();
            Integer value = entry.getValue();
             System.out.print(key + ":" + value + " ");
         }
         System.out.println();
     }
 
     // map遍历-迭代器与entry
     private static void iteratorEntryTravelse(Map<String, Integer> map) {
         Set<Entry<String, Integer>> set = map.entrySet();
         Iterator<Entry<String, Integer>> it = set.iterator();
         while (it.hasNext()) {
            Entry<String, Integer> en = it.next();
            String key = en.getKey();
             Integer value = en.getValue();
            System.out.print(key + ":" + value + " ");
         }
         System.out.println();
     }

posted on 2019-02-21 09:30  城市小农民  阅读(4034)  评论(0编辑  收藏  举报

导航