【问题标题】:How to print all values of specific Hashmap key如何打印特定Hashmap键的所有值
【发布时间】:2014-10-13 14:37:42
【问题描述】:

当前问题:我构建了一个 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)

【问题讨论】:

  • 你为什么要循环播放? HashMap 具有唯一键。一键,一值。
  • 每个键只有 1 个值。 key = value 没有多个条目具有相同的键。
  • 如果你想要一个键有多个值,你应该使用集合类型作为值。
  • 现在你循环整个集合并说如果键存在然后打印当前值。键存在,因此您正在打印每个值。
  • 你想要一个Map&lt;String, List&lt;Example&gt;&gt;

标签: java hashmap


【解决方案1】:

Lars,你的问题是这一行:

            if(mapOfExampleObjects.containsKey(name))

每次您通过循环时,您的 mapOfExampleObjects 将始终包含键“Ian”。你想要的更像是:

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

【讨论】:

  • 是的,也非常正确。
【解决方案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&lt;String,List&lt;Example&gt;&gt;)来针对每个键保留多个值。

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2013-07-25
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多