Java-hashMap的遍历
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String[] args) {
HashMap<Integer, String> integerStringHashMap = new HashMap<>();
integerStringHashMap.put(1,"zhangsan");
integerStringHashMap.put(2,"李四");
integerStringHashMap.put(3,"王五");
integerStringHashMap.put(4,"赵六");
integerStringHashMap.put(4,"王麻子");
//map的第一种遍历方式:利用map.keySet()方法将key值取出,再遍历key值取出value值
// Set<Integer> integers = integerStringHashMap.keySet();
//
// for (Integer key:integers
// ) {
// System.out.println(integerStringHashMap.get(key));
// }
//map的第二种遍历方式:利用map.entrySet()将map转化为set,然后一次取出key和value
Set<Map.Entry<Integer, String>> entries = integerStringHashMap.entrySet();
for (Map.Entry node:entries
) {
System.out.println(node.getKey()+":"+node.getValue());
}
}
}
- 如果要在HashMap或HashSet中放入自己编写的类,则需要重写equals和hashcode方法