手记

Java---两种方法实现遍历Map集合

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapDemo {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    HashMap map = new HashMap();
    map.put("010", "北京");
    map.put("020", "广州");
    map.put("021", "上海");
    map.put("028", "成都");

    //遍历
    //1.先获得键的集合,再取值。
    Set keys = map.keySet();
    Iterator it = keys.iterator();
    while(it.hasNext())
    {
        String code = (String)it.next();
        System.out.println(code+"="+map.get(code));
    }
    System.out.println("\n--------------------------\n");
    //2.获得关系的集合,遍历每一个关系
    Set<Map.Entry<String, String>> sets =  map.entrySet();
    it = sets.iterator();
    while(it.hasNext())
    {
        Entry entry = (Entry)it.next();
        System.out.println(entry.getKey()+"="+entry.getValue());
    }
}

}

7人推荐
随时随地看视频
慕课网APP