Why does java.util.Map.values() allow you to delete entries from the returned Collection when it makes no sense to remove a key value pair based on the value? The code which does this would have no idea what key the value(and hence a key) being removed is mapped from. Especially when there are duplicate values, calling remove on that Collection would result in an unexpected key being removed.
Why does java.util.Map.values() allow you to delete entries from the returned Collection when it
Share
I don’t think you’re being imaginative enough. I’ll admit there probably isn’t wide use for it, but there will be valid cases where it would be useful.
As a sample use case, say you had a
Map<Person, TelephoneNumber>calledcontactList. Now you want to filter your contact list by those that are local.To accomplish this, you could make a copy of the map,
localContacts = new HashMap<>(contactList)and remove all mappings where theTelephoneNumberstarts with an area code other than your local area code. This would be a valid time where you want to iterate through thevaluescollection and remove some of the values:What if you wanted to remove all mappings with that value?