Map使用方法-高效遍历

一、Map 是一种键-值对(key-value)集合,用于保存具有映射关系的数据

用法

Map<Object,Object> map = new HashMap<>();
map.put("hello", "hello");
map.put("world","world");
map.put("world","world1");  
//注意,Map的键不能重复,只能存储一个,存储的是map.put("world","world1");  

二、获取key,value

  • entrySet() 获取Map中key的集合,返回Set类型(注意:Set 集合中的元素是不可重复的,与Map中的键不可重复一样,因此返回Set集合)
1. 获取Map中key的集合
Set set = map.entrySet();
  • values() 获取Map中value数据,返回Collection集合
2. 获取Map中value的集合
Collection collet = map.values();

三、遍历Map的三种方式

  • 1.先获取键的Set集合,然后根据键去取值。不推荐,效率低
Set set = map.keySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();){
//先获取键的Set,然后根据键去取值
    Object key = iterator.next();
    String value = (String)map.get(key);
    System.out.println(key + " =" + value);
}

  • 2.先获取键的Set集合,通过迭代器获取每个元素,直接获取Map.Entry 类型元素
    (注:Map(key,value) 就是Map.Entry类型的)【推荐,高效】
HashMap map = new HashMap();
map.put("a","aa");
map.put("b","bb");
map.put("c","cc");

Set set = map.entrySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();){
//直接获取Map.Entry 
    Map.Entry obj = (Map.Entry) iterator.next();
    System.out.println(obj.getKey());
    System.out.println(obj.getValue());
}

  • 3.使用增强的for循环,获取Map.Entry类型元素。【推荐,高效】
Map<String, String> map = new HashMap<String, String>();
map.put("Java入门教程", "http://c.biancheng.net/java/");
map.put("C语言入门教程", "http://c.biancheng.net/c/");

for (Map.Entry<String, String> entry : map.entrySet()) {
    String mapKey = entry.getKey();
    String mapValue = entry.getValue();
    System.out.println(mapKey + ":" + mapValue);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章