三、Java中级--6、Map

2018-05-07  本文已影响0人  cybeyond
集合和map

键值key不可以重复,但是值value可以重复。

1、HashMap读取方式

package javastudy;

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

public class MyTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HashMap<String, String> cities=new HashMap<String,String>();
        cities.put("010", "北京");
        cities.put("021", "上海");
        cities.put("022", "重庆");
        cities.put("023", "天津");
        Set<String> zips=cities.keySet();
        Iterator<String> it=zips.iterator();  //遍历键
        while(it.hasNext()){
            String zip=it.next();
            String cityName=cities.get(zip);
            System.out.println(zip + ":"+cityName); //得到键的集合
        }
    }
}
执行结果
package javastudy;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class MyTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HashMap<String, String> cities=new HashMap<String,String>();
        cities.put("010", "北京");
        cities.put("021", "上海");
        cities.put("022", "重庆");
        cities.put("023", "天津");
        Collection<String>cityNames=cities.values();//cityNames存放所有城市的名称
        Iterator<String> it=cityNames.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}
执行结果
package javastudy;

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

public class MyTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HashMap<String, String> cities=new HashMap<String,String>();
        cities.put("010", "北京");
        cities.put("021", "上海");
        cities.put("022", "重庆");
        cities.put("023", "天津");
        Set<Entry<String, String>> entries=cities.entrySet();
        Iterator<Entry<String, String>> it=entries.iterator();
        while(it.hasNext()){
            Entry<String, String> entry=it.next(); //不能使用it.next指向两次
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
    }
}
执行结果
上一篇 下一篇

猜你喜欢

热点阅读