遍历集合的几种形式

遍历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(Map<String,String> map){
  
  
  for(String key:map.keySet()){
   System.out.println("test1(): "+key);
  }
 }
 //for循环遍历value
 public void test2(Map<String,String> map){
  for(String value:map.values()){
   System.out.println("test2(): "+value);
  }
 }
 
 //for循环遍历entrySet,获取key和value
 public void test3(Map<String,String> map){
  for(Map.Entry<String, String> entry:map.entrySet()){
   System.out.println("test3(): "+entry.getKey()+":"+entry.getValue());
  }
 }
 //用Iterator遍历
 public void test4(Map<String,String> map){
  Iterator<Map.Entry<String, String>> it= map.entrySet().iterator(); 
  while(it.hasNext()){
   Map.Entry<String, String> entry=it.next();
   System.out.println("test4():"+entry.getKey()+":"+entry.getValue());
  }
 }
 public static void main(String[] args){
  
  Map<String,String> map=new HashMap<String,String>();
  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(): c
test1(): a
test2(): bb
test2(): cc
test2(): aa
test3(): b:bb
test3(): c:cc
test3(): a:aa
test4():b:bb
test4():c:cc
test4():a:aa

 

posted @ 2018-06-25 14:10  第二人生Bonnie  阅读(246)  评论(0编辑  收藏  举报