从哈希图中删除给定值的所有项目

从哈希图中删除给定值的所有项目

本文介绍了从哈希图中删除给定值的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个如下的 java hashmap:

So I have a java hashmap like below:

hMap.put("1", "One");
hMap.put("2", "Two");
hMap.put("3", "Two");

我想删除值为二"的所有项目

I would like to remove ALL items where the value is "Two"

如果我这样做:

hmap.values().remove("Two");

只删除了第一个,我想全部删除,怎么办?

Only the first one is deleted, I want to remove them all, how can this be done?

推荐答案

hmap.values().removeAll(Collections.singleton("Two"));

这种简洁方法的(显着)缺点是你基本上被迫评论它,说类似

the (significant) disadvantage with this concise approach is that you are basically forced to comment it, saying something like

//remove("Two") 只会删除第一个

否则,某天某个好心的工程师会尝试为您简化它并破坏它.发生这种情况...有时善意的行善者甚至是未来的你!

otherwise, some well-meaning engineer will try to simplify it for you someday and break it. This happens... sometimes the well-intentioned do-gooder is even Future You!

这篇关于从哈希图中删除给定值的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:51