【问题标题】:How can I iterate over a map of <String, POJO>?如何遍历 <String, POJO> 的映射?
【发布时间】:2011-04-29 01:41:09
【问题描述】:

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

Person 看起来像:

class Person
{
  String name;
  Integer age;

  //accessors
}

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

System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));
  • A 是 MapString, Person>
  • 的键
  • B 是来自 Person.getName() 的名称
  • C 是来自 Person.getAge() 的年龄

我可以使用 HashMap docs 中详述的 .values() 从地图中提取所有值,但我有点不确定如何获取密钥

【问题讨论】:

    标签: java map hashmap pojo


    【解决方案1】:

    你可以使用:

    例子:

    Map<String, Person> personMap = ..... //assuming it's not null
    Iterator<String> strIter = personMap.keySet().iterator();
    synchronized (strIter) {
        while (strIter.hasNext()) {
            String key = strIter.next();
            Person person = personMap.get(key);
    
            String a = key;
            String b = person.getName();
            String c = person.getAge().toString();
            System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      What about 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());
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-11
        • 2020-07-23
        • 2017-03-21
        • 2012-05-14
        • 1970-01-01
        • 2011-01-09
        • 2020-08-19
        • 1970-01-01
        相关资源
        最近更新 更多