HashMap.containsValue - What#39;s the point?(HashMap.containsValue - 有什么意义?)
问题描述
我有一个 HashMap,我需要通过它的整数值来获取一个项目.我注意到有一个 containsValue() 函数,但看来我仍然必须遍历地图才能找到正确的索引.
I've got a HashMap and I need to fetch an item by its integer value. I notice there's a containsValue() function, but it would appear I still have to iterate through the map to find the correct index anyway.
我的问题是;如果我之后需要遍历它,为什么还要使用 containsValue()?
My question is; why use containsValue() if I'm required to traverse it afterwards?
另外,我是否完全错过了重点?;-)
Also, am I missing the point completely? ;-)
推荐答案
映射将键映射到值.如果你有一个值并且你知道地图包含这个值,为什么你还需要这个键?
A map maps a key to a value. If you have a value and you know the map contains this value, why do you need the key anymore?
另一方面,如果你真的需要key或者你只有value的一个属性,你可以迭代entrySet(),检查value,如果找到就返回key:
On the other hand, if you really need the key or you have just a property of the value, you can iterate the entrySet(), check the value and return the key if found:
for (Map.Entry<Index,Value> entry : map.entrySet()) {
if (entry.getValue().getXy().equals(xy)) {
return entry.getKey();
}
}
这篇关于HashMap.containsValue - 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HashMap.containsValue - 有什么意义?
基础教程推荐
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
