s-day04-Map集合的第二种遍历方式(键值对遍历)
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
package com.inmind.map01;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/*
|
||||
4.Map集合的第二种遍历方式(键值对遍历)
|
||||
- public Set<Map.Entry<K,V>> entrySet():获取到Map集合中所有的键值对对象的集合(Set集合)。
|
||||
*/
|
||||
public class MapDemo03 {
|
||||
public static void main(String[] args) {
|
||||
//创建K和V都是字符串的双列集合
|
||||
Map<String,String> maps = new HashMap<>();
|
||||
maps.put("刘备","孙尚香");
|
||||
maps.put("吕布","貂蝉");
|
||||
maps.put("张飞","夏侯驰");
|
||||
//遍历:先获取所有的键值对对象,然后对键值对对象进行遍历(间接遍历)
|
||||
Set<Map.Entry<String, String>> entries = maps.entrySet();
|
||||
//迭代器遍历'
|
||||
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, String> entry = iterator.next();
|
||||
System.out.println(entry.getKey()+"=="+entry.getValue());
|
||||
}
|
||||
System.out.println("--------------");
|
||||
//foreach循环
|
||||
for (Map.Entry<String,String> entry : entries) {
|
||||
System.out.println(entry.getKey()+"=="+entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user