Java-集合框架-map1
阿新 • • 發佈:2020-08-03
package cn.burce.HashMap; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; //Map的實現類HashMap public class Mapdemo1 { public static void main(String[] args) { fun(); fun1(); } public static void fun() { Map<String, Integer> map = newHashMap<String, Integer>(); map.put("abc", 1); map.put("abcd", 2); map.put("abcde", 3); map.put("abcde", 4); map.put("abcdef", 4); System.out.println(map);// 列印map System.out.println(map.get("abcde"));// 通過鍵取值,沒有鍵返還null } public staticvoid fun1() { HashMap<String, Integer> map = new HashMap<>(); map.put("測試1", 1); map.put("測試2", 2); map.put("測試3", 3); map.put("測試4", 4); // 迭代器的步驟取值 Set<String> set = map.keySet(); Iterator<String> it = set.iterator();while (it.hasNext()) { String s = it.next(); int i = map.get(s); System.out.println(s + "...." + i); } System.out.println("----------------------------------"); // 程式碼簡化的foreach取值 for (String key : map.keySet()) { System.out.println(key + "...." + map.get(key)); } } }