首页 > 其他分享 >【code基础】HashMap用法

【code基础】HashMap用法

时间:2022-09-30 18:45:33浏览次数:54  
标签:map code HashMap System value 用法 遍历 key println

1.hashMap赋值的简便方法

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (maps.containsKey(c)) maps.put(c,maps.get(c)+1);
            else maps.put(c,1);
        }

使用map.getOrDefault(key,自定义值) //若表中存在key,则返回对应的value,不存在,则返回自定义值改造

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            maps.put(c,maps.getOrDefault(c,0)+1);
        }

2.hashMap按照插入的顺序获取插入的第一个元素

1.定义LinkedHashMap 可以按照插入的顺序存储
2.使用map.entrySet().iterator().next()获取第一个entry

    @Test
    //LinkedHashMap 可以按照插入的顺序存储
    public void testHashMap(){
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("welcome","to");
        map.put("java","study");
        map.put("wechat","best396975802");

        Map.Entry entry = map.entrySet().iterator().next();
        String key = (String)entry.getKey();
        String value = (String)entry.getValue();
        System.out.println("key is "+ key); //key is welcome
        System.out.println("value is "+ value); //value is to

    }

3.hashMap的遍历

  1. 通过for遍历map.keySet(),有了key就能通过 map.get(key)得到value
  2. 通过for遍历map.values(),直接拿到vaule
  3. 通过for遍历map.entrySet来取Key和value,获得key为entry.getKey(),获得value为entry.getValue() 推荐的方法
  4. 通过map的forEach遍历 map.forEach((key,value)->
    @Test
    //map的遍历
    public void reverseMap(){
        //一般来说,最好初始化一下, 小于12的就不要初始化了
        // 默认的就是16,因为加载因子是0.75,也就是到16*0.75=12的时候会扩容
        Map<String, String> map = new HashMap<>(3);

        map.put("welcome","to");
        map.put("java","study");
        map.put("wechat","best396975802");

        //遍历方法1: 先遍历key , 再取出value
        System.out.println("遍历方法1: 先遍历key , 再取出value");
        for (String key : map.keySet()) {
            System.out.println("key is "+key);
            System.out.println("value is "+ map.get(key));
        }

        //遍历方法2: 直接遍历value
        System.out.println("遍历方法2: 直接遍历value");
        for (String value : map.values()) {
            System.out.println("value is "+value);
        }

        //遍历方法3: 通过遍历entry来取Key和value,推荐的方法!!!
        System.out.println("遍历方法3: 通过遍历entry来取Key和value,推荐的方法!!!");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("key is "+entry.getKey());
            System.out.println("value is "+ entry.getValue());
        }

        //遍历方法4: 通过forEach方法直接遍历key和value
        System.out.println("遍历方法4: 通过forEach方法直接遍历");
        map.forEach((key,value)->{
            System.out.println("key is "+ key);
            System.out.println("value is "+ value);
        });
    }

标签:map,code,HashMap,System,value,用法,遍历,key,println
From: https://www.cnblogs.com/xiaoyu-jane/p/16745776.html

相关文章