HashMap使用小结

1. HashMap 基本用法         

增 — map.put("4", "c");
删 — map.remove("4");
改 — map.put("4", "d");//覆盖
查 — res.get('a');     //查找对应键值
map.containsKey("2"
); //boolean    map.containsValue("b"); //boolean
容量- map.size();
判空- map.isEmpty();
输出- System.out.println(map);
System.out.println(map.keySet()+" "); //集合中所有键以Set集合形式返回
System.out.println(map.values()+" "); //集合中所有值以Collection集合形式返回
清空- map.clear();
更新键值- map
.put(root.val,res.getOrDefault(root.val,0)+1);
如果不存在则插入 map.putIfAbsent(4, "Weibo");
复制- new_hash_map.putAll(exist_hash_map)

2. HashMap 遍历

第一种方法:使用keySet()

(1) For-Each

Set <String> keys = map.keySet();  //map.keySet()返回key的集合
    for(String key:keys) {
        System.out.println(key+":"+map.get(key));  //map.get(key)返回key所对应的value值
    }

(2) 迭代器

    Set <String> keys = map.keySet();
    Iterator<String> it = keys.iterator();
    String key;
    while (it.hasNext()) {
        key = it.next();
        System.out.println(key+":"+map.get(key));                           
    }

第二种方法:使用entrySet()

这种方法只遍历了1次,它把key和value都放到了entry中,因此比keySet()快。

(1) For-Each

    Set<Entry<String,String>> entrySet = map.entrySet();  //map.entrySet()返回<key,value>键值对的集合
    for (Entry<String,String> entry:entrySet) {
        System.out.println(entry.getKey()+":"+entry.getValue());  //entry.getKey()返回key,entry.getValue()返回value
    }

//要写成 Map.Entry<Integer,Integer> entry:p1.entrySet() 

(2) 迭代器

    Set<Entry<String,String>> entrySet = map.entrySet();
    Iterator<Entry<String,String>> it = entrySet.iterator();
    Entry<String,String> entry;
    while (it.hasNext()) {
        entry = it.next();
        System.out.println(entry.getKey()+":"+entry.getValue());
    }

总结:当map中容量较大时,推荐使用第二种entrySet()的方法。

https://blog.csdn.net/weixin_43263961/article/details/86427533

https://www.runoob.com/java/java-hashmap.html

 

posted on 2021-02-08 11:16  大鱼与小鱼  阅读(65)  评论(0)    收藏  举报

导航