java - 从 Java HashMap 中删除零值

标签 java hashmap

<分区>

我有一个带有浮点值的 HashMap

HashMap<Integer,Float> map : {(1,0.0),(2,0.0),(3,2000.0),(4,3000.0)}

我想删除其中所有值为零的条目。 结果应该是:

 map : {(3,2000.0),(4,3000.0)}

更新:我正在使用 Java 7

最佳答案

从 Java 8 开始,您可以简单地使用

map.values().removeIf(f -> f == 0f);

根据JavaDoc这将删除 map 中满足给定谓词的所有元素。

编辑
当你更新你的问题时,你正在使用 Java 7 在 values() 上使用 Iterator:

Iterator<Float> iterator = map.values().iterator();
while (iterator.hasNext()) {
    if (iterator.next() == 0f) {
        iterator.remove();
    }
}

这是可行的,因为根据 JavaDoc map.values()

Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

关于java - 从 Java HashMap 中删除零值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53442185/

相关文章:

java - 设置 JMenu 方向 RTL

python - 使用预计算针对特定用例优化 Python 算法

java - 用 Map 中的 RegEx 键替换所有出现的字符串

java - 在linux上使用ant编译时出错: wrong version 52. 0,应该是50.0

java - 为什么我们可以在 java 中创建从 sealed(scala) 派生的新类?

java - 注入(inject) URL() Spring Autowired

java - HashSet.clear() 未按预期工作

jsf - 在 h :dataTable 中使用 java.util.Map

spring-boot - 在 Spring Boot Rest API 中将 Map 用作 @RequestBody 不起作用

java - 最佳实践 : Design pattern for 2D HUD screen navigation