获取Map的key值的几种方式

发布时间:2022-08-19 13:39

  1. 调用keySet方法:
	@Test
    public void getKeys1(){
        Map<String, Object> map = new HashMap<>();
        map.put("name","曹操");
        map.put("sex","男");
        map.put("age","21");
        System.out.println("map.keySet():"+map.keySet());
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()){
            System.out.println("iterator:"+iterator.next());
        }
        Set<String> keySet = map.keySet();
        // 遍历keySet,并输出key的值
        for(String key : keySet){
            System.out.println(key+":"+map.get(key).toString());
        }
    }

输出:

map.keySet():[sex, name, age]
iterator:sex
iterator:name
iterator:age
sex:男
name:曹操
age:21
  1. entrySet()
    @Test
    public void getKeys2(){
        Map<String, Object> map = new HashMap<>();
        map.put("name","曹操");
        map.put("sex","男");
        map.put("age","21");
        //第二种
        System.out.println("map.entrySet():"+map.entrySet());
        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            System.out.println("iterator:"+iterator.next());
        }
        for (Map.Entry<String, Object> entry : map.entrySet()){
            System.out.println("key:"+entry.getKey()+";value:"+entry.getValue());
        }
    }

输出:

map.entrySet():[sex=男, name=曹操, age=21]
iterator:sex=男
iterator:name=曹操
iterator:age=21
key:sex;value:男
key:name;value:曹操
key:age;value:21

参考链接:
https://www.cnblogs.com/cailijuan/p/10687995.html

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号