public class TestMap {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("1","a");
        map.put("2","s");
        map.put("3","d");
        map.put("4","f");

        System.out.println("取出所有key----------");
        for (String key :map.keySet()){
            System.out.println(key +"---" + map.get(key));
        }

        System.out.println("取出所有value----------");
        for (String value : map.values()) {
            System.out.println("值:" + value);
        }

        System.out.println("取出所有key和value----------");
//        取出对应的 key,value 键值对,容量大时推荐使用
        for (Map.Entry<String,String> entry : map.entrySet()){
            System.out.println("key:" + entry.getKey());
            System.out.println("value:" + entry.getValue());
        }
    }

}

keySet 其实是遍历了 2 次,一次是转为 Iterator 对象,另一次是从 hashMap 中取出key 所对应的 value;entrySet 只是遍历了一遍

相关文章:

  • 2022-12-23
  • 2021-11-30
  • 2021-11-30
  • 2021-09-20
  • 2021-12-10
  • 2021-12-01
  • 2021-06-11
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-20
  • 2021-09-20
  • 2021-12-15
  • 2021-07-17
  • 2022-12-23
相关资源
相似解决方案