若想遍历HashMap中的元素,需要用到entrySet方法或keySet方法或values方法
1.entrySet方法用于获取键值对
2.keySet方法用于获取键
3.values方法用于获取值
遍历方式主要有两种,迭代器与增强for循环(底层使用迭代器实现)
另外,通过entrySet方法获取的数据类型为实现了Map.Entry接口的HashMap.Node类,getKey、getValue、setValue等方法均系HashMap.Node类重写
迭代器:
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
Set<Map.Entry<String, Object>> entries = map.entrySet();
Set<String> set = map.keySet();
Collection<Object> values = map.values();
System.out.println("=====entrySet=====");
Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
System.out.println("key=" + next.getKey() + " value=" + next.getValue());
}
System.out.println("=====keySet=====");
Iterator<String> iterator1 = set.iterator();
while (iterator1.hasNext()) {
String next = iterator1.next();
System.out.println("key=" + next);
}
System.out.println("=====values=====");
Iterator<Object> iterator2 = values.iterator();
while (iterator2.hasNext()) {
Object next = iterator2.next();
System.out.println("value=" + next);
}
}
增强for循环:
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
Set<Map.Entry<String, Object>> entries = map.entrySet();
Set<String> set = map.keySet();
Collection<Object> values = map.values();
System.out.println("=====entrySet=====");
for (Map.Entry<String, Object> object : entries){
System.out.println("key=" + object.getKey() + " value=" + object.getValue());
}
System.out.println("=====keySet=====");
for (String object : set){
System.out.println("key=" + object);
}
System.out.println("=====values=====");
for (Object object : values){
System.out.println("value=" + object);
}
System.out.println("=====println map=====");
System.out.println(map);
}
运行效果: