Crina Hojda
Crina Hojda

Reputation: 43

Removing from a hashmap a specific value and the key

I want to remove a specific value from the hashmap and the key from that value. Look, for example if I have

hashMap.put(cold, frozen)
hashMap.put(cold,hard)

, in my graphic interface i will have cold=[frozen,hard].If I want to erase hard I want cold = [frozen] to stay

My hashMap is private HashMap<String,ArrayList<String>> hashMap ; Here is what I tried but it's not good enough because if I have at 2 different key the value i want to remove, it only removes the value for the first and if I have for ex cold=[frozen,hard] and I erase hard it doesn't keep cold=[frozen];

for(String key : hashMap.keySet()){
    int siz = hashMap.get(key).size();
    for(int i = 0; i< siz;i++){

        if(hashMap.get(key).get(i).equals(cuvant)){
            s.remove(hashMap.get(key).get(i));
            siz--;
            hashMap.remove(key);

        }
    }
}

I forgot to mention that s is the arrayList with the values.

Upvotes: 2

Views: 5777

Answers (3)

Shailej Shimpi
Shailej Shimpi

Reputation: 145

Are you putting an ArrayList with the values in a hashmap?

If so, then check for list size first:

if (! hashMap.get(key).isEmpty()){
            hashMap.get(key).remove(ValueToRemoved)
 }

Upvotes: 2

karim mohsen
karim mohsen

Reputation: 2254

Try this :-

        HashMap<String, ArrayList<String>> m = new HashMap<>();
        Iterator<Map.Entry<String,ArrayList<String>>> iter = m.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String,ArrayList<String>> entry = iter.next();
            ArrayList<String> list = entry.getValue();
            for(int i = 0 ; i < list.size() ; i++){
                if(list.get(i).equals(cuvant)){
                    list.remove(i);
                }
            }
            if(list.isEmpty())
                iter.remove();
        }

Upvotes: -1

amit
amit

Reputation: 178451

add a condition

if (hashMap.get(key).isEmpty())

before

hashMap.remove(key);

This will ensure you delete a key only if the list associated with it is completely empty.


Also, make sure you do NOT keep iterating (the inner loop) after removing an element from the list if you use a for-each loop, it will get you a ConcurrentModificationException. If your list can have the same value multiple times (and should be removed multiple times), use the Iterator API rather than for-each loop.

Upvotes: 0

Related Questions