从值不是我在寻找的HashMap中删除所有条目 [英] Remove all entries from HashMap where value is NOT what I'm looking for

查看:50
本文介绍了从值不是我在寻找的HashMap中删除所有条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题问题很好地总结了一下,但是假设我正在用Java编写代码,并且有一个HashMap看起来像这样(显然有很多条目):

The title question summarizes it nicely, but assume I am coding in Java and have a HashMap that looks something like this (it has a lot more entries obviously):

Map<String, Integer> myMap = new HashMap<>();

myMap.put{"a", 1}
myMap.put{"b", 2}
myMap.put{"c", 2}
myMap.put{"d", 3}

现在我不喜欢值为2的条目,因此我想尽可能有效地删除它们 all ,只剩下那些具有值1或3.

Now I don't like entries with the value of 2, so I want to remove them all as effectively as possible, leaving me only with the entries that have value 1 or 3.

看起来好像我的地图是这样制作的:

It should look as if my map was instead made like this:

Map<String, Integer> myMap = new HashMap<>();

myMap.put{"a", 1}
myMap.put{"d", 3}

好像我的2值条目根本就不存在!

As if my 2-valued entries were never there at all!

以有效方式执行此操作有哪些选择?

What are my options for doing this in an effective way?

推荐答案

map.entrySet().removeIf(entry -> entry.getValue() == 2)

这篇关于从值不是我在寻找的HashMap中删除所有条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆