HashMap集合的遍历

来源:互联网 发布:淘宝紫砂壶店铺 编辑:程序博客网 时间:2024/06/05 00:49

首先说明 , HashMap底层依赖的是hash算法 , 其存储是无序的 , 所以hashmap集合并不能保证怎么存就怎么取 .
hashmap集合常用的遍历方式有两种:

  • 通过键找值
 public void bianli(View view) {    Map<String, Integer> map = new HashMap<>();        map.put("张三", 23);        map.put("李四", 24);        map.put("王五", 25);        map.put("赵六", 26);        Set<String> keySet = map.keySet(); //获取所有键的集合        Iterator<String> it = keySet.iterator();//获取迭代器        while (it.hasNext()) {      //判断集合是否有元素            String key = it.next(); //获取每一个键            Integer value = map.get(key); //根据键获取值            System.out.println(key + "=" + value);        }    }

也可以简化成如下的代码:

 public void bianli(View view) {    Map<String, Integer> map = new HashMap<>();        map.put("张三", 23);        map.put("李四", 24);        map.put("王五", 25);        map.put("赵六", 26);    for (String key : map.keySet()) {//map.ketSet()是所有键的集合            System.out.println(key + "=" + map.get(key));        }    }
  • 根据键值对对象 , 获取键和值
思路:*获取所有键值对对象的集合;*遍历键值对对象的集合,获取到每一个键值对对象*根据键值对对象找键和值public void bianli(View view) {    Map<String, Integer> map = new HashMap<>();        map.put("张三", 23);        map.put("李四", 24);        map.put("王五", 25);        map.put("赵六", 26);     //Map.Entry说明Entry是Map的内部类,将键和值分装成了Entry对象,并存储在Set集合中    Set<Map.Entry<String, Integer>> entrySet = map.entrySet();        //获取每一个对象   Iterator<Map.Entry<String, Integer>> it = entrySet.iterator();        while (it.hasNext()) {            //获取每一个Entry对象            Map.Entry<String, Integer> entry = it.next();            String key = entry.getKey();//根据键值对对象获取键            Integer value = entry.getValue();//根据键值对对象获取值            System.out.println(key + "=" + value);        }    }

这种方式也可以简化 , 代码如下:

 public void bianli(View view) {    Map<String, Integer> map = new HashMap<>();        map.put("张三", 23);        map.put("李四", 24);        map.put("王五", 25);        map.put("赵六", 26);    for (Map.Entry<String, Integer> en : map.entrySet()) {           System.out.println(en.getKey() + "=" + en.getValue());        }    }
1 0
原创粉丝点击