要从哈希图中删除键和值吗?

问题描述 投票:-3回答:2

我正在用Java编写程序。因此,有一个特定的方法和一个HashMap。填充Hashmap的方法无关紧要。

public static HashMap<Integer, String> names = new HashMap<>();

所以我的目标是,有第二种方法,该方法从我的HashMap中删除Value以及String。问题是,我的第二种方法只知道键(字符串)。也许我可以举个例子:

public void remove(String s) {
names.remove(s);
}

所以,正如您所看到的,有第二种方法。它应该删除密钥以及值。另外,应该说,我不想清除完整的Hashmap,因为其中保存了很多名称。希望您了解我的问题,并且可能有答案:)

java string hashmap key key-value
2个回答
1
投票

您应该首先搜索具有传递值的项目以获取密钥,然后将其删除。这是一个例子:

    public static HashMap<Integer, String> names = new HashMap<>();
    public static void main(String[] args) {
        names.put(1,"john");
        names.put(2,"bob");
        names.put(3,"john");
        remove("john");
        System.out.println(names);
    }
    private static void remove(String str) {
        int key = getKeyByValue(str);
        while(key > -1) {
            names.remove(key);
            key = getKeyByValue(str);
        }
    }
    private static int getKeyByValue(String str) {
        int itemKey = -1;
        for(HashMap.Entry<Integer,String> name : names.entrySet()) {
            if(str.equals(name.getValue())) {
                itemKey = name.getKey();
                break;
            }
        }
        return itemKey;
    }

输出为:

{2=bob}

-2
投票

查看您的代码,Hashmap的密钥是Integer类型的,而不是String类型的。从Hashmap中删除键值对仅相当于执行以下操作-

names.remove(key);

如果您希望将值返回给您,则可以编写-

String value = (String)names.remove(key); 
© www.soinside.com 2019 - 2024. All rights reserved.