java如何打印特定Hashmap键的所有值
当前问题:我构建了一个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)
# 1 楼答案
拉尔斯,你的问题是这句话:
每次通过循环时,mapOfExampleObjects始终包含键“Ian”。你想要的更像:
# 2 楼答案
您可以提取映射的
keySet
并对其进行操作以选择所需的条目:请注意,这仍然只会打印一个
Ian
,因为Map
对每个键只保留一个值。您需要使用不同的结构(可能是Map<String,List<Example>>
)来针对每个键保留多个值