public class Demo01 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("01", "this is 01");
//第一种遍历方式 获取key-value 放入entry中 从而获取键值
Set<Entry<String,String>> set = map.entrySet();
for(Entry<String,String> entry : set) {
System.out.println("key is : "+entry.getKey()+",value is "+entry.getValue());
}
System.out.println("------------------------------------------------------");
//第二种遍历方式 只获取key 再从map中获取value
for(String key :map.keySet()) {
System.out.println("key is : "+key+",value is "+map.get(key));
}
System.out.println("------------------------------------------------------");
//第三种遍历方式 只获取value
for(String value : map.values()) {
System.out.println("value is "+value);
}
System.out.println("------------------------------------------------------");
//第四中遍历方式 迭代器遍历
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
Entry<String, String> next = it.next();
//这样的写法不合理 应为这样写会调用多次next 所以导致越界 然后报错java.util.NoSuchElementException
//System.out.println("key is : "+it.next().getKey()+",value is "+it.next().getValue());
System.out.println("key is : "+next.getKey()+",value is "+next.getValue());
}
}
}