遍历Map的两种方法
如果单独遍历map的key推荐使用getKey(Map map)方法
1 package com.learn.java.map; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.Set; 7 8 /** 9 * 10 * 遍历map的key和value 11 * @Author: HAOHAORUI 12 * @Date: Create in 2:21 PM 2021/1/14 13 * @Email: rhh0809@163.com 14 */ 15 public class Maplearn02 { 16 17 public static void main(String[] args) { 18 Map map = new HashMap(); 19 20 map.put("aa","11"); 21 22 map.put("bb","22"); 23 24 //遍历map的key和value 25 getKeyAndValue(map); 26 27 //遍历map中的key 28 getkey(map); 29 30 31 32 } 33 34 /** 35 * 遍历map的key和value 36 * @param map 37 */ 38 public static void getKeyAndValue(Map map){ 39 Set<Map.Entry<String,String>> set = map.entrySet(); 40 41 Iterator<Map.Entry<String,String>> iterable = set.iterator(); 42 43 while (iterable.hasNext()){ 44 Map.Entry<String,String> entry = iterable.next(); 45 46 System.out.println(entry.getKey()+"--"+entry.getValue()); 47 } 48 } 49 50 /** 51 * 遍历map中的key 52 * @param map 53 */ 54 private static void getkey(Map map){ 55 Set<String> setkeys = map.keySet(); 56 57 for (String key:setkeys){ 58 System.out.println(key+"--"+map.get(key)); 59 } 60 61 62 } 63 }

浙公网安备 33010602011771号