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

发布时间 2023-05-10 11:09:25作者: 我的心儿

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移除值------------------------");
    Collection<String> collect = map.values();
    System.out.println(map);
    if (collect.contains("郭富城") == true) {
        collect.remove("郭富城");
    }
    System.out.println(map);