Printing HashMap In Java

后端 未结 15 1656
半阙折子戏
半阙折子戏 2020-11-28 19:32

I have a HashMap:

private HashMap example = new HashMap();

Now I would lik

相关标签:
15条回答
  • 2020-11-28 19:54

    You want the value set, not the key set:

    for (TypeValue name: this.example.values()) {
            System.out.println(name);
    }
    

    The code you give wouldn't even compile, which may be worth mentioning in future questions - "doesn't seem to work" is a bit vague!

    0 讨论(0)
  • 2020-11-28 19:56

    You can use Entry class to read HashMap easily.

    for(Map.Entry<TypeKey, TypeKey> temp : example.entrySet()){
        System.out.println(temp.getValue()); // Or something as per temp defination. can be used
    }
    
    0 讨论(0)
  • 2020-11-28 19:58

    To print both key and value, use the following:

    for (Object objectName : example.keySet()) {
       System.out.println(objectName);
       System.out.println(example.get(objectName));
     }
    
    0 讨论(0)
提交回复
热议问题