Map

Map概述:

接口Map<k,v>

类型参数:

k-此映射所维护的键的类型    v-映射值的类型

Map集合:该集合存储键值对。一对一对往理存。而且要保证键的唯一性。

嵌套类摘要:

static interface Map.Entry<k,v>  映射项(键-值对)

方法摘要:

1,void clear():从此映射中移除所有映射关系(可选操作)。

2,boolean containsKey(Object Key):如果此映射包含指定键的映射关系,则返回true。

3,boolean containsValue(Object Value):如果此映射将一个或多个键映射到指定值,则返回true。

4,Set<Map.Entry<k,v>> entrySet():返回此映射中包含的映射关系的Set视图。

5,boolean equals(Object o):比较指定的对象与此映射是否相等。

6,V get(Object key):返回指定键所映射的值,如果此映射不包含该键的映射关系,则返回null。//可以通过get方法的返回值来判断一个键是否存在。通过返回null来判断。

7,int hashCode():返回此映射的哈希码值。

8,boolean isEmpty():如果此映射未包含键值映射关系,则返回true。

9,Set<k> keyset():返回此映射中包含的键的Set视图。

10,V put(K key,V value):将指定的值与此映射中的指定键关联(可选操作)。//添加元素时出现相同的键,那么新值会覆盖原有键对应值。并会返回被覆盖值。

11,void putAll(Map<? extends K,? extends V> m):从指定映射中将所有映射关系复制到此映射中(可选操作)。

12,V remove(Object Key):如果存在一个键的映射关系,则将其从此映射中移除(可选操作)。

13,int size():返回此映射中的键-值映射关系数。

14,Collection<V> values():返回此映射中包含的值的Collection的视图。

 Map子类对象特点

1,HashTable:此类实现一个哈希表,该哈希表将键映射到相对应的值。任何非null对象都可以用作键或值。为了成功地在哈希表中存储和获取对象,用作键的对象必须实现hashCode和equals方法。该集合是线程同步的。JDK1.0效率低。

2,HashMap:基于哈希表的Map接口的实现,允许使用null值和null键。(除了非同步和允许使用null之外,HashMap类和HashTable大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。该集合是不同步的。JDK1.2效率高。

3,TreeMap:底层是二叉树数据结构,线程不同步。可以用于给Map集合中的键进行排序。

和Set很像,其实Set底层就是使用了Map集合。

 Map集合的两种取出方式

1,Set<k> keySet:讲Map中所有的键存入到Set集合,因为set具备迭代器,所以可以通过迭代方式取出所有的键,根据get的方法获取每一个键对应的值。

Map集合的取出原理:将Map集合转成Set集合,再通过迭代器取出。

2,Set<Map.Entry<K,V>> entrySet:将Map集合中的映射关系存入到Set集合中,而这个关系的数据类型就是Map.Entry。

关系对象Map.Entry获取到后,就可以通过Map.Entry中getKey和getValue方法获取关系中的键和值。

Map.Entry:其实Entry也是一个接口,它是Map接口中的一个内部接口。  

接口方法摘要:

1,boolean equals(Object o):比较指定对象与此项的相等性。

2,K getKey():返回与此项对应的键。

3,V getValue():返回与此项对应的值。

4,int hashCode():返回此映射项的哈希码值。

5,V setValue(V value):用指定的值替换与此项对应的值(可选操作)。

 Map练习

 一,每一个学生都有一个对应的归属地。学生Student,地址String。学生属性:姓名,年龄。注意:姓名和年龄相同的视为同一个学生。保证学生的唯一性。

 步骤:1,描述学生。2,定map容器,将学生作为键,地址作为值,存入。3,获取map集合中的元素。

 

 

import java.util.*;
calss Student implements Comparator<Student>
{
    private String name;
    private int age;
    Student(String name,int age)
    {
        this.name = name;
        this.age = age;  
     }  
    public int CompareTo(Student s)
    {
        int num = new Integer(this.age).compareTo(new Integer(s.age));
        if(num==0)
             return this,name.compareTo(s.name);
        return num;
    }
    public int hashCode()
    {
        return name.hashCode()+age*34;
    }
    public boolean equals(Object obj)
    {
        if(!(obj instanceOf Student))
            throw ClassCastException("类型不匹配");
        Student s = (Student)obj;
        return this.name,equals(s.name) && this.age==s.age;
    }
    
    public String getName()
    {
        return name;
    }
    public int age()
    {
        return age;
    }
    public String toString()
    {
        return name+":"+age;
    }
}

calss MapTest
{
   public static void main(String [] args)
   {
        HashMap<Student,String> hm = new HashMap<Student,String>();
        hn,put(new Student("lisi1",21),"beijing");
        hn,put(new Student("lisi2",22),"shanghai");  
        hn,put(new Student("lisi3",23),"nanjing");
        hn,put(new Student("lisi4",24),"wuhan");

        //第一种取出方式 keyset
        Set<Student> ketset = hm.keyset();
        Iterator<Student> it = ketset.iterator();
        while(it.hasNext())
        {
            Student stu = it next();
            String addr = hm.get(stu);
            System.out.println(stu+".."+addr);
        }
 }         
}                    

 

//第二种取出方式:entrySet
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Emtry<Student,String>> iter = entrySet.iterator();
while(iter.hasNext())
{
    Map.Entry<Student,String> me = iter.next();
    Student stu = me.getKey();
    String addr = me.getValue();
    System.out.println(stu+"......."+addr);   
}

 TreeMap练习一

 需求:对学生对象的年龄进行升序排序。

因为数据是以键值对存在的,所以要使用可以排序的的Map集合。TreeMap。

 

import java.util.*;
class MapTest2
{
    public static void main(String [] args)
    {
        TreeMap<Student,String> tm = new TreeMap<Student,String>();
        tm.put(new Stydent("lisi3",23),"nanjing");
        tm.put(new Stydent("lisi1",21),"beijing");
        tm.put(new Stydent("lisi4",24),"wuhan");
        tm.put(new Stydent("lisi2",22),"shanghai");
        Set<Map.Entry<Student,String>> entrySet = tm.entrySet();
        Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
        while(it.hasNext())
       {
            Map.Entry<Student,String> me = it.next();
            Student stu = me.getKey();
            String assr = me.getValue();
            System.out.println(stu+":::"+addr)
       }

    }
}    

 

 

 根据需求的不同,自定义姓名比较器。

 

class StuNameConparator implements Comparator<Student>
{
    public int compare(Student s1,Student s2)
    {
        int nun = s1.getName().compareTo(s2.getName());
        if(num==0)
            return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
        return num;
    }
}    
     //   TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameConparator()); 

 


 

 TreeMap练习二

 "sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。

希望打印结果:a(1)c(2)......

通过结果发现,每一个字母都有对应的额次数。说明字母和次数之间都有映射关系。

注意了,当发现有映射关系时,可以选择map集合,因为map集合中存放的就是映射关系。

什么时候使用map集合呢?当数据之间存在这种映射关系时,就要先想map集合。

思路:

1,将字符串转换成字符数组,因为要对每一个字母进行操作。

2,定义一个map集合,因为打印结果的字母有顺序,所以使用TreeMap集合。

3,遍历字符数组。

  1,将每一个字母作为键去查map集合。

  2,如果返回null,将该字母和1存入到map集合中。

  3,如果返回不是null,说明该字母在map集合已经存在并有对应次数。那么就获取该次数并进行自增。然后将该字母和自增后的次数存入map集合中,覆盖原来键所对应的值。

  4,将map集合中的数据变成指定的字符串形式返回。

import java.util.*;
class MapTest3
{
    public static void main(String [] args)
    {
        charCount("aabfcdabcdefa");
    }    

    public static String charCount(String str)
    {
        char [] chs = str.toCharArray();
        TreeMap<Chatacter,Integer> tm = new TreeMap<Character,Integer>();

    int count = 0;

    for(int x = 0;x<chs.length;x++)
    {
        if(!(chs[x]>='a' && chs[x]<='z' || chs[x]>='A' && chs[x]<='Z'))
            continue;
            
        Integer value = tm.get(chs[x]);
        
        if(value!=0)
            count = value;
        counu++;
        tm.put(chs[x],count);
        conut = 0;//用完后防止数据叠加
        /*
        if(value==null)
        {
             tm. put(chs[x],1);    
         }
        else
        {
             value = value + 1;
             tm.put(chs[x],value); 
        }
        */


    }    
    StringBulider sb = new StringBulider();
    Set<Map.Entry<Character,Integer>> entrySet =  tm.enteySet();

    Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();

    while(it.hasNext())
    {
         Map.Entry<Character,Integer> me = it.next();
         Character ch = me.getKey();
         Integer value = me.getValue();
         sb.append(ch+"("+value+")");
    }
    return sb.toString();
    }
}

 

 

 Map扩展知识

 map集合被使用是因为具备映射关系。

"yurenban" "01" "zhangsan"

"yurenban" "02" "lisi"

"jiuyeban" "01" "wangwu"

"jiuyeban" "02" "zhaoliu"

 

import java.util.*;

class MapDemo3
{
    pubilc static void main(String [] args)
    {
        HashMap<String,<String,String>> czbk = new HashMap<String,<String,String>>();

        HashMap<String,String> yure = new HashMap<String,String>();

         HashMap<String,String> jiuye = new HashMap<String,String>();

        czbk.put("yureban","yure");
        czbk.put("jiuyeban","jiuye");

        yure.put("01","zhangsan");
        yure.put("02","lisi");
       
        jiuye.put("01","zhaoliu");
        jiuye.put("02","wangwu");


        //遍历czbk集合,获取所有的教室。
        Iterator<String> it = czbk.keySet().iterator;
        while(it.next())
        {
            String roomName = it.next();
            HashMap<String,String> room = czbk.get(roomName);
            getStudentInfo(room);    

         }

        //getStudentInfo(yure);
    }
    pubilc ststic void getStudentInfo(HashMap<String,String> roomMap)
    {
        Iterator<String> it = roomMap.keySet().iterator();
        while(it.hasNext())
        {
            String id = it.next();
            String name = roomMap.get(id);
            System.out.println(id+":"+name); 
        }

    }





}

 在实际开发当中,通常将Student封装成对象。代码如下:

import java.util.*;
class Student
{
    private String id;
    private String name;
    Student(String id,String name)
    {
        this.id = id;
        this.name = name;
    }
    public String toString()
    {
        return id+":::"+name;
    }
}


class MapDemo3
{
    pubilc static void main(String[] arg)
    {
        demo();
    }   


    public static void demo()
    {
        HashMap<String,List<Student>> czbk = new HashMap<String,<Student>>();

        List<Student> yure = new ArrayList<Student>();
        List<Student> jiuye = new ArrayList<Student>();

        czbk.put("yureban",yure);
        czbk.put('jiuyeban",jiuye);

        yure.add(new Student("01","zhangsan");
        yure.add(new Student("02","wangwu");
        jiuye.add(new Student("01","zhouqi");
        jiuye.add(new Student("02","zhapliu");

        Iterator<String> it = czbk.keySet().iterator();
        while(it.hasNext())
        {
            String roomName = it.next();
            List<Student> room = czbk.get(roomName);
            System.out.println(roomName);
            getInfos(room); 
         }
    }

    public static void getInfos(List<Student> list)
    {
        Iterator<Student> it = list.iterator();
        while(it.hasNext())
        {
            Student s = it.next();
            System.out.println(s);      
        }
 
    }
}

 

 

 

 

 

 

 

 

.....

posted on 2015-09-13 15:20  大爱卓生  阅读(163)  评论(0编辑  收藏  举报