How can I iterate over a map of lt;String, POJOgt;?(我如何遍历 lt;String, POJOgt; 的映射?)
问题描述
我有一个 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());
}
这篇关于我如何遍历 <String, POJO> 的映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何遍历 <String, POJO> 的映射?


基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01