閬嶅巻hashmap鐨勬柟寮忔湁鍝簺
閬嶅巻HashMap鐨勬柟寮忔湁浠ヤ笅鍑犵锛?/p>
- 浣跨敤Iterator閬嶅巻锛氬彲浠ラ€氳繃
entrySet()
鏂规硶鑾峰彇涓€涓寘鍚墍鏈夐敭鍊煎鐨凷et闆嗗悎锛岀劧鍚庨€氳繃Iterator杩唬鍣ㄩ亶鍘嗛泦鍚堜腑鐨勫厓绱狅紝鑾峰彇閿€煎銆?/li>
HashMap<String, Integer> map = new HashMap<>();
// 娣诲姞閿€煎
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
// 澶勭悊閿€煎
}
- 浣跨敤閿泦鍚堥亶鍘嗭細鍙互閫氳繃
keySet()
鏂规硶鑾峰彇涓€涓寘鍚墍鏈夐敭鐨凷et闆嗗悎锛岀劧鍚庨€氳繃閬嶅巻闆嗗悎涓殑閿潵鑾峰彇瀵瑰簲鐨勫€笺€?/li>
HashMap<String, Integer> map = new HashMap<>();
// 娣诲姞閿€煎
for (String key : map.keySet()) {
Integer value = map.get(key);
// 澶勭悊閿€煎
}
- 浣跨敤鍊奸泦鍚堥亶鍘嗭細鍙互閫氳繃
values()
鏂规硶鑾峰彇涓€涓寘鍚墍鏈夊€肩殑Collection闆嗗悎锛岀劧鍚庨€氳繃閬嶅巻闆嗗悎涓殑鍊兼潵澶勭悊瀵瑰簲鐨勯敭鍊煎銆?/li>
HashMap<String, Integer> map = new HashMap<>();
// 娣诲姞閿€煎
for (Integer value : map.values()) {
// 澶勭悊鍊?/span>
}
- 浣跨敤Java 8鐨刦orEach閬嶅巻锛氬彲浠ヤ娇鐢↗ava 8鐨刦orEach鏂规硶鏉ラ亶鍘咹ashMap涓殑閿€煎銆?/li>
HashMap<String, Integer> map = new HashMap<>();
// 娣诲姞閿€煎
map.forEach((key, value) -> {
// 澶勭悊閿€煎
});