定义一个map集合,key为String类型的姓名,value为String类型地址,存入数据多条数据(假设不存在重名的情况),并用多种方式遍历
public class Demo01Map {
public static void main(String[] args) {
//创建Map集合
Map<String,String> map=new HashMap();
map.put("AA","aa");
map.put("BB","bb");
map.put("CC","cc");
System.out.println(map);
System.out.println("===============");
//第一种遍历方法:entrySet();
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry:entrySet){
System.out.println(entry);
}
System.out.println("===============");
//第二种遍历方法:keySet();
Set<String> keySet = map.keySet();
for (String key:keySet){
System.out.println(key+"-"+map.get(key));
}
System.out.println("===============");
//第三种遍历方法:迭代器
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> next=iterator.next();
System.out.println(next.getKey()+"=="+next.getValue());
}
}
}
测试: