遍历list集合:
遍历map集合:遍历map集合有以下几种方式。
package asi;import java.util.Iterator;import java.util.Map;import java.util.HashMap;public class TestMapBianLi { //for遍历key public void test1(Mapmap){ for(String key:map.keySet()){ System.out.println("test1(): "+key); } } //for循环遍历value public void test2(Map map){ for(String value:map.values()){ System.out.println("test2(): "+value); } } //for循环遍历entrySet,获取key和value public void test3(Map map){ for(Map.Entry entry:map.entrySet()){ System.out.println("test3(): "+entry.getKey()+":"+entry.getValue()); } } //用Iterator遍历 public void test4(Map map){ Iterator > it= map.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry=it.next(); System.out.println("test4():"+entry.getKey()+":"+entry.getValue()); } } public static void main(String[] args){ Map map=new HashMap (); map.put("a", "aa"); map.put("b", "bb"); map.put("c", "cc"); TestMapBianLi t=new TestMapBianLi(); t.test1(map); t.test2(map); t.test3(map); t.test4(map); } }
输出结果为:
test1(): b
test1(): ctest1(): atest2(): bbtest2(): cctest2(): aatest3(): b:bbtest3(): c:cctest3(): a:aatest4():b:bbtest4():c:cctest4():a:aa