2

私は持っていますMap<String, Person>(実際には、より複雑なPOJOを使用していますが、質問のために単純化しています)

Person次のようになります。

class Person
{
  String name;
  Integer age;

  //accessors
}

このマップを反復処理して、キー、人の名前、年齢などを出力するにはどうすればよいですか。

System.out.println(String.format("Key : %s Name : %s Age : %s", a, b, c));
  • A は Map< String , Person>のキーです
  • B は Person.getName() の名前です
  • C は Person.getAge() の年齢です

HashMap docsで詳しく説明されているように、 .values() を使用してマップからすべての値を取得できますが、キーを取得する方法が少しわかりません

4

2 に答える 2

9

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());

}
于 2010-10-22T09:24:15.277 に答える
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));

    }
}
于 2010-10-22T09:33:49.467 に答える