Map集合遍历一
Map的遍历方式:键找值方式
Map接口定义方法:Set keySet(),Map集合的键取出,存储在Set集合
/*
* Map集合方法keySet()遍历
* 步骤:
* 1.Map集合方法keySet()获取 存储键的Set集合
* 2.遍历Set集合
* 3.取出Set集合的元素,是Map的键
* 4.Map集合键,找值
*/
public class MapDemo02 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("abc", 123);
map.put("bcd", 124);
map.put("cde", 125);
//1.Map集合方法keySet()获取 存储键的Set集合
Set<String> set = map.keySet();
//2.遍历Set集合
Iterator<String> it = set.iterator();
while(it.hasNext()) {
//3.取出Set集合的元素,是Map的键
String key = it.next();
//4.Map集合键,找值
Integer value = map.get(key);
System.out.println(key+"="+value);
}
}
}
Map集合遍历二
键值对的映射关系遍历:Map.Entry接口,实现类对象表示了键值对的对应关系,拿到Map.Entry接口实现类对象.
- Entry接口的方法
K getKey()
取出集合中的键V getValue()
取出集合中的值
- Map接口定义的方法
Set<Map.Entry<K,V>> entrySet()
集合中的键值对映射关系对象,Entry接口对象,存储在Set集合
/*
* Map集合的遍历,键值对的映射关系
* 步骤:
* 1.Map集合方法的entrySet() 获取到Entry接口实现类对象,存储Set集合
* 2.遍历Set集合
* 3.取出Set集合中的元素,是Entry接口的实现类对象(键值对的对应关系)
* 4.Entry接口对象,调用方法getKey(),getValue()
*/
public class MapDemo03 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("abc", 123);
map.put("bcd", 124);
map.put("cde", 125);
//1.Map集合方法的entrySet() 获取到Entry接口实现类对象,存储Set集合
Set<Map.Entry<String, Integer>> set = map.entrySet();
//2.遍历Set集合
Iterator<Map.Entry<String, Integer>> it = set.iterator();
while(it.hasNext()) {
//3.取出Set集合中的元素,是Entry接口的实现类对象(键值对的对应关系)
Map.Entry<String, Integer> entry = it.next();
//4.Entry接口对象,调用方法getKey(),getValue()
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"="+value);
}
}
}