开发者

hashMap in Java

开发者 https://www.devze.com 2023-02-12 03:30 出处:网络
I wanna do that: Method will be deleteLeafValue where it will get Object value. This will search all the sub hashMap values and clear all items wher开发者_如何学JAVAe third value is Object value.

I wanna do that: Method will be deleteLeafValue where it will get Object value. This will search all the sub hashMap values and clear all items wher开发者_如何学JAVAe third value is Object value.

   public void put(K1 key1, K2 key2, V value)
{
    HashMap<K2, V> childMap = get(key2);
    if (childMap == null)
    {
        childMap = new HashMap<K2, V>();
        put(key1, childMap);
    }
    childMap.put(key2, value);
}

How can i do deleteLeafValue method?


Do you mean?

public void remove(K1 key1, K2 key2) {
    Map<K2, V> childMap = get(key2);
    if (childMap != null) 
       childMap.remove(key2);
}

or

public void removeByValue(V value) {
    for(Map<K2, V> childMap : values())
       for(Iterator<V> valueIter = childMap.values(); valueIter.hasNext();)
           if(valueIter.next().equals(value))
               valueIter.remove();
}

You might find using a composite key is simpler

Map<String, String> extendedMap = new HashMap<String, String>();
extendedMap.put("Row1/Column1", "French");
extendedMap.put ("Row1/Column2", "English");
extendedMap.put ("Row1/Column3", "Spanish");
extendedMap.put ("Row2/Column1", "John");
extendedMap.put ("Row2/Column2", "Richard");
extendedMap.put ("Row3/Column3", "Cole");

extendedMap.remove("Row3/Column3");


I don't think you should extend HashMap, you should manage an existing Map implementation from the outside:

Add the leaves

public static <V, K1, K2> V put(final Map<K1, Map<K2, V>> outerMap,
    final K1 outerKey,
    final K2 innerKey,
    final V value){
    Map<K2, V> innerMap = outerMap.get(outerKey);
    if(innerMap == null){
        innerMap = new HashMap<K2, V>();
        innerMap.put(innerKey, value);
        outerMap.put(outerKey, innerMap);
        return null;
    }
    return innerMap.put(innerKey, value);
}

Delete leaves by value

/** Returns the number of deletions that were made */
public static <V, K1, K2> int deleteLeafValues(
    final Map<K1, Map<K2, V>> outerMap,
    final V value){

    int deleted = 0;
    for(final Map<K2, V> innerMap : outerMap.values()){
        final Iterator<Entry<K2, V>> iterator =
            innerMap.entrySet().iterator();
        while(iterator.hasNext()){
            if(iterator.next().getValue().equals(value)){
                iterator.remove();
                deleted++;
            }
        }

    }
    return deleted;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消