我如何遍历 <String, POJO> 的映射? [英] How can I iterate over a map of <String, POJO>?

查看:28
本文介绍了我如何遍历 <String, POJO> 的映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Map<String, Person>(实际上我使用的是更复杂的 POJO,但为了我的问题而对其进行了简化)

I've got a Map<String, Person> (actually I'm using a more complex POJO but simplifying it for the sake of my question)

Person 看起来像:

class Person
{
  String name;
  Integer age;

  //accessors
}

我如何遍历这张地图,打印出密钥,然后是人名,然后是人的年龄,例如:

How can I iterate through this map, printing out the key, then the person name, then the person age such as :

System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));

  • A 是 MapString、Person>
  • 的键
  • B 是来自 Person.getName() 的名称
  • C 是来自 Person.getAge() 的年龄
  • 我可以使用 .values() 从地图中提取所有值,详见 HashMap docs,但我有点不确定如何获取密钥

    I can pull all of the values from the map using .values() as detailed in the HashMap docs, but I'm a bit unsure of how I can get the keys

    推荐答案

    entrySet() 呢

    HashMap<String, Person> hm = new HashMap<String, Person>();
    
    hm.put("A", new Person("p1"));
    hm.put("B", new Person("p2"));
    hm.put("C", new Person("p3"));
    hm.put("D", new Person("p4"));
    hm.put("E", new Person("p5"));
    
    Set<Map.Entry<String, Person>> set = hm.entrySet();
    
    for (Map.Entry<String, Person> me : set) {
      System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());
    
    }
    

    这篇关于我如何遍历 &lt;String, POJO&gt; 的映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆