Java中HashMap的常用操作

前期准备:首先给hashMap里面put一些键值对,代码如下:

HashMap<Integer, Integer> hashMap = new HashMap<>();
        
        hashMap.put(5, 2);
        hashMap.put(9, 2);
        hashMap.put(8, 1);
        hashMap.put(7, 3);
        hashMap.put(16, 1);
        hashMap.put(10, 2);
        hashMap.put(6, 2);
        //其实下面两个键值对是没有存的
        hashMap.put(5, 2);
        hashMap.put(5, 3);

当在hashmap中put的key在之前已经存过,则不会重复存储,会覆盖之前key对应的value,详情请参照源码
1.containsKey(Object key)方法,返回值为boolean,用于判断当前hashmap中是否包含key对应的key-value

2.containsValue(Object value)方法,返回值为boolean,用于判断当前hashmap中是否包含value对应的key-value

3.遍历hashmap的两种方式:

(1)利用haspmap.entrySet().iterator():利用迭代器,从Entry中取出键、取出值,推荐使用这种方式进行遍历,效率较高

Iterator<Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<Integer, Integer> entry = iterator.next();
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            System.out.print(key + "--->" + value);
            System.out.println();
        }
(2)利用hashmap.keySet().iterator():利用键的迭代器,每次取出一个键,再根据键,从hashmap中取出值,这种方式的效率不高,不推荐使用
Iterator<Integer> iterator2 = hashMap.keySet().iterator();
        while (iterator2.hasNext()) {
            Integer key = iterator2.next();
            Integer value = hashMap.get(key);
            System.out.print(key + "---" + value);
            System.out.println();
        }


--------------------- 
作者:Logan24 
来源:CSDN 
原文:https://blog.csdn.net/u013398759/article/details/77679632 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_42551740/article/details/89791028