- /*
- * Map集合的获取功能测试
- *
- * V get(Object key):用一个key查找对应的值;
- * Set<K> keySet():返回所有键的Set集合;
- * Collection<V> values():获取所有value的集合;
- * Set<Map.Entry<K,V>> entrySet():获取所有"键值对对象";
- *
- * Map的遍历方式只有两种:
- * 1.keySet:先获取所有键的集合,然后遍历键的集合,根据每个键去获取值;
- * 2.entrySet:获取所有的"键值对对象"的集合,然后遍历;
- *
- */
- public class Demo {
- public static void main(String[] args) {
- Map<String,String> map = new HashMap<>();
- map.put("it001", "刘德华");
- map.put("it002", "张学友");
- map.put("it003", "章子怡");
- map.put("it004", "撒贝宁");
-
- // System.out.println("获取it004对应的值:" + map.get("it004"));
-
- //遍历Map集合的一种方式:
- Set<String> keys = map.keySet();
- for(String key : keys){
- System.out.println(key + "----" + map.get(key));
- }
- System.out.println("------------Map.Entry遍历--------------");
- //遍历Map集合的第二种方式:
- Set<Map.Entry<String,String>> entrySet = map.entrySet();
- for(Map.Entry<String,String> en : entrySet){
- System.out.println(en.getKey() + "---" + en.getValue());
- }
-
- }
- }
复制代码 |
|