Map集合按key删除和按value删除

codeLearn / 2023-05-10 / 原文

点击查看代码
 public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("name1", "刘德华");
        map.put("name2", "黎明");
        map.put("name3", "张学友");
        map.put("name4", "郭富城");
        System.out.println("-----------------Map中按key移除值------------------------");
        System.out.println(map);
        for (String s : map.keySet()) {
            if (s == "name1") {
                map.remove("name1");
            }
        }
        System.out.println(map);
        System.out.println("-----------------Map中按value移除值------------------------");
        Map<String, String> map1 = new HashMap<>();
        map1.put("name1", "刘德华");
        map1.put("name2", "黎明");
        map1.put("name3", "张学友");
        map1.put("name4", "郭富城");
        System.out.println(map1);
        Collection<String> collect = map1.values();
        if (collect.contains("张学友") == true) {
            collect.remove("张学友");
        }
        System.out.println(map1);

    }