要从HashMap中删除指定的元素,可以使用以下方法:
HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.remove("A"); System.out.println(hashMap); // 输出:{B=2} HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.remove("A", 1); System.out.println(hashMap); // 输出:{B=2} HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("A", 1); hashMap.put("B", 2); Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); if (entry.getKey().equals("A")) { iterator.remove(); } } System.out.println(hashMap); // 输出:{B=2} 以上是几种常见的方法来删除HashMap中的指定元素,选择适合自己需求的方法来实现元素的删除。