有四种遍历方式
第一种方式:KeySet()方法
第二种方式:entrySet()方法
第三种方式:forEach(BiConsumer)方法
第四种方式: values(); 获取集合中所有值,返回到一个Collection集合中。forEach()方法
import java.util.*;
public class text {
public static void main(String[] args) {
HashMap<String,String> hm=new HashMap<String, String>();
hm.put("hm001","张三");
hm.put("hm002","李四");
hm.put("hm003","王五");
//第一种方式:KeySet()方法
Set<String> keys=hm.keySet();
for (String key:keys){
String value=hm.get(key);
System.out.println(key+""+value);
}
System.out.println("===============");
//第二种方式:entrySet()方法
Set<Map.Entry<String,String>> entrys=hm.entrySet();
Iterator<Map.Entry<String,String>> it=entrys.iterator();
while (it.hasNext()){
Map.Entry<String,String> entry=it.next();
String key=entry.getKey();
String value=entry.getValue();
System.out.println(key+"="+value);
}
System.out.println("===============");
//第三种方式:forEach(BiConsumer)方法
hm.forEach((String key,String value)->{System.out.println(key+"="+value);});
System.out.println("===============");
//第四种方式: values(); 获取集合中所有值,返回到一个Collection集合中。forEach()方法
Collection<String> values=hm.values();
values.forEach((String value)->{System.out.println(value);});
}
}