首页 > 代码库 > hashmap的遍历

hashmap的遍历

  • 通过键找值
    package com.baidu.demo;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Set;
    //通过键找值
    public class Demo01 {
        public static void main(String[] args) {
            HashMap<String, String> map = new HashMap<>();
            map.put("一", "老大");
            map.put("二", "老二");
            map.put("三", "老三");
            //foreach循环遍历
            Set<String> keySet = map.keySet();
            for (String string : keySet) {
                System.out.println(string+"====="+map.get(string));
            }
            //iterator遍历
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String string = (String) iterator.next();
                System.out.println(string+"======"+map.get(string));
                
            }
            
        }
    }

     

  • 通过键值对找值
    package com.baidu.demo;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    //通过键值对找值
    public class Demo01 {
        public static void main(String[] args) {
            HashMap<String, String> map = new HashMap<>();
            map.put("一", "老大");
            map.put("二", "老二");
            map.put("三", "老三");
            //foreach循环遍历
            Set<Entry<String, String>> entrySet = map.entrySet();
            for (Entry<String, String> entry : entrySet) {
                System.out.println(entry.getKey()+"===="+entry.getValue());
            }
            //iterator遍历
            Iterator<Entry<String, String>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String,String> entry = (Map.Entry<String,String>) iterator.next();
                System.out.println(entry.getKey()+"====="+entry.getValue());
            }
        }
    }

     

hashmap的遍历