package com; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * 遍历Map * @author Administrator */ public class IterateMapKey { public static void main(String[] args) { Map<String,Integer> map = new HashMap<String,Integer>(); //添加3个元素 map.put("k1", 1); map.put("k2", 2); map.put("k3", 3); System.out.println("-----获取所有的key------"); Set<String> keys = map.keySet(); for( String key : keys ){ System.out.println("key:" + key+",value:"+ map.get(key)); } System.out.println("-----获取所有 key-value------"); //java.util.Map.Entry Set<Entry<String,Integer> > entries = map.entrySet(); //获取用于遍历Set集合的迭代器 Iterator<Entry<String,Integer>> it = entries.iterator(); while(it.hasNext()){ //遍历每一组键值对 Entry<String,Integer> entry = it.next(); String key = entry.getKey(); int value = entry.getValue(); System.out.println(key+"="+value); } System.out.println("-----返回的所有value不是存入的Set集合------"); Collection<Integer> values = map.values(); for(Integer value : values){ System.out.println("value:"+value); } } } |
|