3、[简答题] 【Map接口中的常用方法】 请使用Map集合的方法完成添加元素,根据键删除,以及根据键获取值操作。


package day_04_test;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//3、[简答题]
//【Map接口中的常用方法】
//请使用Map集合的方法完成添加元素,根据键删除,以及根据键获取值操作。
public class Demo03 {
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(1,"张三");
        map.put(2, "李四");
        map.put(3, "王五");
        System.out.println(map);
        //根据键值删除元素
        map.remove(1);
        System.out.println(map);
        //根据键获取值
        //方法一:遍历键
        Set keySet = map.keySet();
        for (Integer integer:keySet
             ) {
            String value = map.get(integer);
            System.out.println(integer+"="+value);
        }
        //方法二:遍历键值对
        Set> entrySet = map.entrySet();
        for (Map.Entry entry:entrySet
             ) {
            System.out.println(entry.getKey()+"="+entry.getValue());
        }
    }
}

相关