例1:
package Test15; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; //Map集合遍历 public class Test { private Map<String, String> map = new HashMap<String, String>(); public static void main(String[] args) { Test t=new Test(); t.setValue(); t.method3(); } //为map赋值 public void setValue(){ map.put("name", "张三"); map.put("sex", "男"); } //方法1 public void method1(){ Set<String> set = new HashSet<String>(); set = map.keySet(); // 获得map中所有Key for (String s : set) { System.out.println(map.get(s)); } } //方法2 public void method2(){ Iterator<String> iterator=map.keySet().iterator(); //返回所有key while(iterator.hasNext()){ String key=iterator.next(); System.out.println(key+": "+map.get(key)); } } //方法3 public void method3(){ Set<Entry<String,String>> set= map.entrySet(); //返回:key和value的封装 for(Entry entry:set){ System.out.println(entry.getKey()+":"+entry.getValue()); } } }
来源:https://www.cnblogs.com/gdds/p/3643943.html