public class HashMapDemo {标签:未加泛,遍历,JAVA,HashMap,System,hashMap,println,out From: https://www.cnblogs.com/wang1999an/p/16826484.html
public static void main(String[] args) {
HashMap hashMap = new HashMap();
hashMap.put("小吉祥草王", "纳西妲");
hashMap.put("岩王爷", "摩拉克斯");
hashMap.put("雷神", "巴尔");
//HashMap的四种遍历方式
//method1(hashMap);//forEach的lambda表达式遍历
//method2(hashMap);//keySet遍历
//method3(hashMap);//迭代器遍历
method4(hashMap);//entrySet遍历
}
private static void method4(HashMap hashMap) {
Set entrySet = hashMap.entrySet();
for (Object obj :entrySet) {
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey()+"-"+entry.getValue());
}
}
private static void method3(HashMap hashMap) {
Set entrySet = hashMap.entrySet();
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()) {
//Object entry = iterator.next();
// System.out.println(entry);
Object entry = iterator.next();
Map.Entry m = (Map.Entry) entry;
System.out.println(m.getKey() + "-" + m.getValue());
}
}
private static void method2(HashMap hashMap) {
Set set = hashMap.keySet();
for (Object objKey : set) {
System.out.println(objKey + "-" + hashMap.get(objKey));
}
System.out.println("--------values-----");
Collection values = hashMap.values();
for (Object objValue : values) {
System.out.println(objValue);
}
}
private static void method1(HashMap hashMap) {
System.out.println("forEach方便遍历");
hashMap.forEach((key, value) -> {
System.out.println(key + "-" + value);
});
}
}