1 package com.test; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 7 public class Test { 8 9 public static void main(String[] args) throws Exception { 10 11 Map<String,String> map = new HashMap<String,String>(); 12 map.put("a","a1"); 13 map.put("a","a2"); 14 map.put("b","b1"); 15 map.put("c","c1"); 16 17 System.out.println("-----获得全部key-----"); 18 System.out.println(map.keySet()); 19 System.out.println("-----获得全部value-----"); 20 System.out.println(map.values()); 21 22 System.out.println("-----keySet-----"); 23 for(String key : map.keySet()) { 24 System.out.println(key + ":" + map.get(key)); 25 } 26 27 System.out.println("-----entrySet-----"); 28 for(Map.Entry<String, String> entry : map.entrySet()) { 29 System.out.println(entry.getKey() + ":" + entry.getValue()); 30 } 31 32 System.out.println("-----iterator-----"); 33 //使用iterator遍历 好处是可以删除元素 使用foreach时删除元素则会报错 34 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); 35 while(it.hasNext()) { 36 Map.Entry<String, String> entry = it.next(); 37 System.out.println(entry.getKey() + ":" + entry.getValue()); 38 //it.remove(); //删除元素 39 } 40 System.out.println("-----Lambda-----"); 41 map.forEach((key, value) -> { 42 System.out.println(key + ":" + value); 43 }); 44 } 45 }
原文地址:https://www.cnblogs.com/chenkaixin12121/p/9605824.html
时间: 2024-10-08 19:51:02