当前问题:我构建了一个 HashMap 来保存和检索一些键和值。但我不确定如何通过特定名称(字符串)检索所有值。目前它正在打印 Hashmap 中的所有值,但这不是我想要实现的目标。
在下面的示例中,我使用以下字段
字段
String name
// Object Example
HashMap
Map<String,Example> mapOfExampleObjects = new HashMap<String,Example>();
for 循环通过某个键名称从 HashMap 中检索值
for(Map.Entry<String,Example> entry: mapOfExampleObjects.entrySet()){
if(mapOfExampleObjects.containsKey(name))
{
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
电流输出
John + (Exampleobject)
Ian + (Exampleobject)
Ian + (Exampleobject)
Jalisha + (Exampleobject)
我想要实现的输出
Ian + (Exampleobject)
Ian + (Exampleobject)
最佳答案
拉尔斯,你的问题是这一行:
if(mapOfExampleObjects.containsKey(name))
每次执行循环时,您的 mapOfExampleObjects 将始终包含键“Ian”。你想要的更像是:
if( name.equals(entry.getKey()) )
关于java - 如何打印特定Hashmap键的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26342580/