java_基础_遍历map删除元素_Java 遍历Map(包括集合)时,修改删除元素

时间:2025-02-08 12:45:06
public staticvoid main(String[] args) { // 构建一个Map 初始值为3条数据 Map map = new HashMap(); map.put("1", "xiaqiu"); map.put("2", "pangzi"); map.put("3", "shouzi"); //第一种:普遍使用,二次取值 System.out.println("通过遍历key和value:"); for (String key : map.keySet()) { System.out.println("key= "+ key + " and value= " + map.get(key)); } //第二种:通过[Iterator](/so/search?q=Iterator&spm=1001.2101.3001.7020)迭代器遍历循环().iterator(); System.out.println("通过使用iterator遍历key和value:"); Iterator> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = it.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } //第三种:笔者推荐,尤其是容量大时(相对来说 比2好一点 效率高) System.out.println("通过遍历key和value"); for (Map.Entry entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); } //第四种 System.out.println("通过()遍历所有的value,但不能遍历key"); for (String v : map.values()) { System.out.println("value= " + v); } }