Map接口
- 定义了双列集合的规范,每次存储一对元素
- Map<K,V> 其中K代表键(key)的类型,V代表键对应的值(value)
- 通过键可以查找到值,且键有唯一性(值可重复)
Map集合遍历
/*
Map集合遍历
1.先创建Map集合名为map,给集合添加值
2.使用Map集合的方法keySet(),把Map集合所有的key键取出来存储于set中
3.开始遍历循环: 有两种方法
4.同时使用Map方法中的get(key),如:map.get(key)来获取key对应的value值
*/
public class Test1 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1,"小明");
map.put(2,"小华");
map.put(3,"小强");
//使用Map集合的方法keySet(),把Map集合所有的key取出来存储在Set集合中
Set<Integer> set = map.keySet();
//循环遍历法1:迭代器
/*Iterator<Integer> it = set.iterator();//创建迭代器
while(it.hasNext()){
Integer key = it.next();
String value = map.get(key);
System.out.println(key+"="+value);
}
*/
//法2:for-each
for (Integer key : set) {
String value = map.get(key);//使用get(key)来获取value值
System.out.println(key+"="+value);
}
}
}