标签:
package cn.sdut.lah; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; public class Demo2 { Map map = null; @Before public void before(){ map = new HashMap();//若要按照存入的顺序输出,则使用linkedHashMap map.put(1, "唐僧"); map.put(2, "猪八戒"); map.put(3, "孙悟空"); } /** * way1: 先获取键集合,由键的到值 */ @Test public void test1(){ //使用迭代器遍历 Set set = map.keySet(); Iterator it = set.iterator(); while(it.hasNext()){ int key = (int) it.next(); String value = (String) map.get(key); System.out.println(key+": "+value); } } @Test public void test11(){ //使用增强for循环遍历 for (Object obj:map.keySet()){ int key = (int) obj; String value = (String) map.get(key); System.out.println(key+": "+value); } } /** * way2:先获取键值对集合,从而得到键和值 */ @Test public void test2(){ //使用迭代器遍历 Set set = map.entrySet(); Iterator it = set.iterator(); while(it.hasNext()){ Map.Entry entry = (Entry) it.next(); int key = (int) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key+": "+value); } } public void test22(){ //使用增强for循环遍历 for (Object obj:map.entrySet()){ Map.Entry entry = (Entry) obj; int key = (int) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key+": "+value); } } @After public void after(){ map = null; } }
标签:
原文地址:http://www.cnblogs.com/lahblogs/p/4228937.html