如何打印特定Hashmap密钥的所有值

时间:2014-10-13 14:37:42

标签: java hashmap

当前问题 :我已经构建了一个HashMap来保存和检索一些键和值。但我不知道如何通过特定名称(String)检索所有值。目前它正在打印Hashmap中的所有值,而这不是我想要实现的。

在下面的示例中,我使用以下字段

字段

String name
// Object Example

HashMap

Map<String,Example> mapOfExampleObjects = new HashMap<String,Example>();

for循环以通过某个键名从哈希映射中检索值

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)

2 个答案:

答案 0 :(得分:4)

Lars,你的问题是这一行:

            if(mapOfExampleObjects.containsKey(name))

您的mapOfExampleObjects将始终包含密钥&#39; Ian&#39;每次你经历循环。你想要的更像是:

if( name.equals(entry.getKey()) )

答案 1 :(得分:2)

您可以提取地图的keySet并对其进行操作以选择所需的条目:

class Example {

    final String name;

    Example(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

public void test() {
    // Sample data.
    Map<String, Example> mapOfExampleObjects = new HashMap<String, Example>();
    mapOfExampleObjects.put("John", new Example("John Smith"));
    mapOfExampleObjects.put("Ian", new Example("Ian Bloggs"));
    mapOfExampleObjects.put("Ian", new Example("Ian Smith"));
    mapOfExampleObjects.put("Jalisha", new Example("Jalisha Q"));
    // Using a Set you can extract many.
    Set<String> want = new HashSet<String>(Arrays.asList("Ian"));
    // Do the extract - Just keep the ones I want.
    Set<String> found = mapOfExampleObjects.keySet();
    found.retainAll(want);
    // Print them.
    for (String s : found) {
        System.out.println(mapOfExampleObjects.get(s));
    }
}

请注意,这仍然只会打印一个Ian,因为Map仅针对每个键保留一个值。您需要使用不同的结构(可能是Map<String,List<Example>>)来为每个键保留多个值。

相关问题