-->

Remove entry from map without iterating

2020-08-14 10:34发布

问题:

How do I remove entry from Java Map without using iteration using value or key. Basically in my map, I am using containsKey() then map.remove() to remove it.

回答1:

You remove an entry from a map by using the key of the element that you wish to remove.

map.remove("aKey");

If you don't know the key of the element you must iterate to obtain it such as this:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
     Set<T> keys = new HashSet<T>();
     for (Entry<T, E> entry : map.entrySet()) {
         if (value.equals(entry.getValue())) {
             keys.add(entry.getKey());
         }
     }
     return keys;
} 

This will return all the keys that were found on the map.



回答2:

Map<Integer, String> abcMap = new HashMap<Integer, String>();
abcMap.put(1,"A");
abcMap.put(2,"B");
abcMap.put(3,"C");

/// now for remove item
abcMap.remove(1);
// this will remove "A" from abcMap..


回答3:

In most cases you can remove entry (key-value pair) from a map using Map.remove(key) method. There will be no iteration over the map. You don't need to use Map.containsKey(key) before the Map.remove(key) because Map.remove already does it. It returns either a previous associated value with key or null if there was no mapping for the key.

But you can't do the same thing using a value only (without key). The only option is to iterate via map and find entry (or entries) with that value.

Java 5-7:

for (Iterator<MyValue> it = map.values.iterator(); it.hasNext(); ) {
    if(it.next().equals(myValue)) {
        it.remove();
    }
}

Java 8:

map.values().removeIf(v -> v.equals(myValue));


回答4:

Use Map#remove(Object key):

public V remove(Object key)

Removes the mapping for this key from this map if it is present (optional operation). More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null : key.equals(k)), that mapping is removed. (The map can contain at most one such mapping.)

Returns the value to which the map previously associated the key, or null if the map contained no mapping for this key. (A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values.) The map will not contain a mapping for the specified key once the call returns.

Basically you can call remove, even if the key does not exist. It will silently fail in that case(returning null). The object need not be identical or the same, if yourKey.equals(key) is true for the key you want to remove.



回答5:

public Object remove(Object key)

remove method in Map.

From javadoc:

Removes the mapping for this key from this map if it is present (optional operation). More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null : key.equals(k)), that mapping is removed. (The map can contain at most one such mapping.)

Returns the value to which the map previously associated the key, or null if the map contained no mapping for this key. (A null return can also indicate that the map previously associated null with the specified key if the implementation supports null values.) The map will not contain a mapping for the specified key once the call returns.

Parameters:

key - key whose mapping is to be removed from the map.

Returns:

Previous value associated with specified key, or null if there was no mapping for key.

Example:

Map<Integer, String> map=new HashMap<>();
    map.put(20, "stackOverflow");
    System.out.println(map.remove(20));

This code will print "stackOverflow" i.e. Previous value associated with specified key. Hope it helps.



回答6:

It seems nobody here actually answered OP's question. They were asking how, without using an iterator, to remove an entry "using value or key". Of course remove(key) works if you have the key, but not if you are searching for a value.

Alfredo's answer was closest, in that it searches the value side of the Map, but it uses an iterator.

Here's a solution using Java 8's Stream API; no iterators:

Map<K, V> newMap = map.entrySet().stream()
    .filter(entry -> !entry.getKey().equals(searchValue))
    .filter(entry -> !entry.getValue().equals(searchValue))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

(Substitute K and V for your key and value types.)



回答7:

Use Map's remove method, which takes a key as an argument. You don't need the original object; you just need an object that compares equal to the existing key in the map with equals, and produces the same hashCode as the existing key in the map.



回答8:

public static void main(String[] args) { //Constant.mapCustomer.remove("s"); Map<String, String> mapCustomer=new HashMap<String, String> ();; mapCustomer.put("s","ss"); System.out.println(mapCustomer.get("s")); mapCustomer.remove("s"); System.out.println(mapCustomer.get("s")); }