简体   繁体   English

在不迭代的情况下从地图中删除条目

[英]Remove entry from map without iterating

How do I remove entry from Java Map without using iteration using value or key.如何在不使用值或键的迭代的情况下从Java Map删除条目。 Basically in my map, I am using containsKey() then map.remove() to remove it.基本上在我的地图中,我使用containsKey()然后map.remove()来删除它。

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.这将返回在地图上找到的所有键。

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..

In most cases you can remove entry (key-value pair) from a map using Map.remove(key) method.在大多数情况下,您可以使用Map.remove(key)方法从地图中删除条目(键值对)。 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.您不需要在Map.containsKey(key)之前使用Map.remove(key)因为Map.remove已经这样做了。 It returns either a previous associated value with key or null if there was no mapping for the key .它返回要么与以前的相关值keynull ,如果有对没有映射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.唯一的选择是通过 map 进行迭代并找到具有该值的条目(或多个条目)。

Java 5-7:爪哇 5-7:

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

Java 8:爪哇 8:

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

Use Map#remove(Object key) :使用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.更正式地说,如果此映射包含从键 k 到值 v 的映射,使得(key==null ? k==null : key.equals(k)) ,则删除该映射。 (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.返回映射先前与键关联的值,如果映射不包含此键的映射,则返回 null。 (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. (如果实现支持 null 值,则返回 null 也可以指示映射先前将 null 与指定的键关联。)一旦调用返回,映射将不包含指定键的映射。

Basically you can call remove, even if the key does not exist.基本上你可以调用remove,即使键不存在。 It will silently fail in that case(returning null).在这种情况下它会默默地失败(返回 null)。 The object need not be identical or the same, if yourKey.equals(key) is true for the key you want to remove.如果您要删除的键的yourKey.equals(key)为真,则对象不必相同或相同。

public Object remove(Object key)

remove method in Map .Map remove方法。

From javadoc :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.更正式地,如果此映射包含从键 k 到值 v 的映射,使得(key==null ? k==null : key.equals(k)),则删除该映射。 (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.返回映射先前与键关联的null如果映射不包含此键的映射,则返回null (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. (如果实现支持null值,则返回null也可以指示映射先前将null与指定的键关联。)一旦调用返回,映射将不包含指定键的映射。

Parameters:参数:

key - key whose mapping is to be removed from the map. key - 要从映射中删除其映射的键。

Returns :回报

Previous value associated with specified key, or null if there was no mapping for key.与指定键关联的先前值,如果没有键映射,则为null

Example:示例:

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

This code will print "stackOverflow" ie Previous value associated with specified key.此代码将打印"stackOverflow"即与指定键关联的先前值。 Hope it helps.希望它有帮助。

It seems nobody here actually answered OP's question.似乎这里没有人真正回答 OP 的问题。 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 .当然,如果您有密钥, remove(key)可以工作,但如果您正在搜索value则不行。

Alfredo's answer was closest, in that it searches the value side of the Map , but it uses an iterator. Alfredo 的答案最接近,因为它搜索Map的值侧,但它使用迭代器。

Here's a solution using Java 8's Stream API;这是使用 Java 8 的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.) (将KV替换为您的键和值类型。)

Use Map 's remove method , which takes a key as an argument.使用Mapremove方法,它将一个键作为参数。 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.您只需要一个对象,该对象将等于映射中的现有键与equals ,并生成与映射中现有键相同的hashCode

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"));
}

assume map is having some entries: : Map<Integer,Character> map = new HashMap<>();假设 map 有一些条目: : Map<Integer,Character> map = new HashMap<>();

  • To remove entry from a map at an index i (without iterating), you would need to convert the map keySet into the list.要从索引 i 处的地图中删除条目(不进行迭代),您需要将地图 keySet 转换为列表。

    List<Map.Entry<Integer , Character>> list = new ArrayList<Map.Entry<Integer,Character>>(map.entrySet()); List<Map.Entry<Integer , Character>> list = new ArrayList<Map.Entry<Integer,Character>>(map.entrySet());

  • get the entry using the index.使用索引获取条目。

    Map.Entry<Integer , Character> entry = list.get(index); Map.Entry<Integer , Character> entry = list.get(index);

  • remove the entry from the map从地图中删除条目

    map.remove(entry.getKey()); map.remove(entry.getKey());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM