【问题标题】:printing a hashmap of a key with multiple values打印具有多个值的键的哈希图
【发布时间】:2023-03-17 14:55:01
【问题描述】:
class hello {
    string name;
    int number;
}

class object {
    public static void main(string args[]) {
        HashMap hs = new HashMap();
        hello c1 = new hello();
        hello c2 = new hello();
        hs.put("india",c1);
        hs.put("america",c2);
    }
}

如何打印键值对

具有多个值的键如何打印

【问题讨论】:

  • HashMap 具有完美的 toString 表示,如果您在 hello 类中覆盖 toString 方法。你也应该覆盖equalshashcode
  • 不要调用类object。也不要叫它Object

标签: java


【解决方案1】:

像这样迭代 MapHashMap

Map<String, Hello> map=new HashMap<>();
Set<Entry<String, Hello>> entries=map.entrySet();
for (Entry<String, Hello> entry : entries) {
    String key=entry.getKey();
    Hello hello=entry.getValue();
}

【讨论】:

    【解决方案2】:

    您需要遍历哈希映射键,然后打印键及其值。

    示例

    HashMap<String, hello> map = new HashMap<String, hello>();
        for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
            String key = iterator.next();
            System.out.println(key + map.get(keu).toString); suppose you already override the toString method in your hello class
        }
    

    【讨论】:

    • 我认为直接遍历entrySet 会更好,因为您不需要每次想要与键关联的值时都重新计算哈希码。 for each 循环也是你的朋友 :)
    【解决方案3】:

    使用 Java 8:

    map.forEach((key, value) -> System.out.println(key + ", " + value));
    

    【讨论】:

      【解决方案4】:

      您也可以使用条目集进行迭代。

       HashMap<String,hello> hs=new HashMap<String, hello>();
       // Put values for hashMap.
       for(Map.Entry<String, hello> printPairs: hs.entrySet()) {
             System.out.print(printPairs.getKey()+" ---- ");
             System.out.println(printPairs.getValue());
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-15
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-04
        • 2011-06-01
        相关资源
        最近更新 更多