Java集合框架(下)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/John_z1/article/details/52013467

上篇博文介绍了Collection集合

http://blog.csdn.net/john_z1/article/details/52013254

这篇博文将介绍Map集合。

Map集合

首先map和collection都是一个接口,具体的实现都由下面的实现类实现功能。它们最大的区别就是collection是单列集合,map是双列集合(泛型参数是一个键—值对)。map集合与set类似,主要有HashMap、TreeMap和HashTable三个实现类,HashTable基本上现在不使用了。

  • Map(接口)
    • HashMap
    • TreeMap
    • HashTable

下面以HashMap为例,介绍三种获得HashMap的值。

public class MapTest { 
    public static void main(String[] args){      
        HashMap<String, String> map=new HashMap<String, String>();      
        map.put("010", "BeiJing");      
        map.put("021", "ShangHai");      
        map.put("012", "TianJin");      
        map.put("043", "ChongQing");      
        map.put("026", "GuangZhou");  

        //方法一:通过map.keySet()方法得到其键  
        Set<String> zips=map.keySet();//得到键  
        Iterator<String> it=zips.iterator();  
        while(it.hasNext())  {   
            String zip=it.next();      
            System.out.println(zip+":"+map.get(zip));
  }

   //方法二:通过map.values()方法得到其值
    Collection<String> cities=map.values();//得到值  
    Iterator<String> it=cities.iterator();  
    while(it.hasNext()){      
        System.out.println(it.next());  

     //方法三:通过map.entrySet()得到键值(即一个条目entry)
    Set<Entry<String, String>> entries=map.entrySet();//得到键值对
    Iterator<Entry<String, String>> it=entries.iterator();
    while(it.hasNext()){
        Entry<String, String> entry=it.next();
        String key=entry.getKey();
        String value=entry.getValue();
        System.out.println(key+":"+value);
        }
}

可以将上面的HashMap修改为TreeMap,其他代码无需修改则可以按顺序输出。

猜你喜欢

转载自blog.csdn.net/John_z1/article/details/52013467