user622222
user622222

Reputation: 131

hashMap in Java

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 where 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?

Upvotes: 0

Views: 1144

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299148

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

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533790

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

Upvotes: 4

Related Questions