黑马程序员-------Java基础-------集合之Map

黑马程序员——Java基础——集合之Map

——- android培训java培训、期待与您交流! ———-

一、Map概述

  1. 简述:Map<>集合是一个接口,和List集合及Set集合不同的是,它是双列集合,并且可以给对象加上名字,即键(Key)。
  2. 特点:
    1)该集合存储键值对,一对一对往里存
    2)要保证键的唯一性。

二、Map集合的子类

Map
|–Hashtable:底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。JDK1.0,效率低。
|–HashMap:底层是哈希表数据结构。允许使用null键null值,该集合是不同步的。JDK1.2,效率高。
|–TreeMap:底层是二叉树数据结构。线程不同步。可以用于给Map集合中的键进行排序。
注意:Map和Set很像。其实Set底层就是使用了Map集合。

三、Map集合的常用方法

1、添加
void put(K key,V value);//添加元素,如果出现添加时,相同的键,那么后添加的值会覆盖原有键对应值,并put方法会返回被覆盖的值。
voidputAll//添加一个集合
2、删除
clear();//清空
voidremove(Object key);//删除指定键值对
3、判断
containsKey(Objectkey);//判断键是否存在
containsValue(Objectvalue)//判断值是否存在
isEmpty();//判断是否为空
4、获取
Vget(Object key);//通过键获取对应的值
size();//获取集合的长度
Collectionvalue();//获取Map集合中所以得值,返回一个Collection集合
还有两个取出方法,接下来会逐个讲解:
Set

四、Map集合的两种取出方式

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

1、Set < K > keySet():将Map中所以的键存入到Set集合。因为Set具备迭代器。所以可以通过迭代方式取出所以键的值,再通过get方法。获取每一个键对应的值。

import java.util.*;  

//描述学生类  
class Student implements Comparable<Student>  
{  
    private String name;  
    private int age;  
    Student(String name,int age)  
    {  
        this.name=name;  
        this.age=age;  
    }  
    public String getName()  
    {  
        return name;  
    }  

    public int getAge()  
    {  
        return age;  
    }  

    //复写hashCode  
    public int hashCode()  
    {  
        return name.hashCode()+age*33;   
    }  
    //复写equals,比较对象内容  
    public boolean equals(Object obj)  
    {  
        if(!(obj instanceof Student))  
            throw new ClassCastException("类型不匹配");  
        Student s=(Student)obj;  
        return this.name.equals(s.name)&&this.age==s.age;  
    }  

    //复写compareTo,以年龄为主  
    public int compareTo(Student c)  
    {  
        int num=new Integer(this.age).compareTo(new Integer(c.age));  
        if(num==0)  
        {  
            return this.name.compareTo(c.name);  
        }  
        return num;  
    }  

    //复写toString,自定义输出内容  
    public String toString()  
    {  
        return name+"..."+age;  
    }  

}  
class  HashMapTest  
{  
    public static void main(String[] args)   
    {  
        HashMap<Student,String > hm=new HashMap<Student,String >();  
        hm.put(new Student("zhangsan",12),"beijing");  
        hm.put(new Student("zhangsan",32),"sahnghai");  
        hm.put(new Student("zhangsan",22),"changsha");  
        hm.put(new Student("zhangsan",62),"USA");  
        hm.put(new Student("zhangsan",12),"tianjing");  

        keyset(hm);  
    }  

    //keySet取出方式  
    public static void keyset(HashMap<Student,String> hm)  
    {  
        Iterator<Student> it=hm.keySet().iterator();  

        while(it.hasNext())  
        {  
            Student s=it.next();  
            String addr=hm.get(s);  
            System.out.println(s+":"+addr);  
        }  
    }  
}  

2、Set< Map.Entry< K,V > > entrySet():将Map集合中的映射关系存入到Set集合中,而这个关系的数据类型就是:Map.Entry
其实,Entry也是一个接口,它是Map接口中的一个内部接口。

interface Map  
    {  
         public static interface Entry  
         {  
              public abstract Object getKey();  
              public abstract Object getValue();  
         }  
 }  

示例:
同上面示例的学生类—-

class  HashMapTest  
{  
    public static void main(String[] args)   
    {  
        HashMap<Student,String > hm=new HashMap<Student,String >();  
        hm.put(new Student("zhangsan",12),"beijing");  
        hm.put(new Student("zhangsan",32),"sahnghai");  
        hm.put(new Student("zhangsan",22),"changsha");  
        hm.put(new Student("zhangsan",62),"USA");  
        hm.put(new Student("zhangsan",12),"tianjing");  

        entryset(hm);  
    }  
//entrySet取出方式  
    public static void entryset(HashMap<Student,String> hm)  
    {  
        Iterator<Map.Entry<Student,String>> it=hm.entrySet().iterator();  

        while(it.hasNext())  
        {  
            Map.Entry<Student,String> me=it.next();  
            Student s=me.getKey();  
            String addr=me.getValue();  
            System.out.println(s+":::"+addr);  
        }  
    }  
} 

注意:Map是一个接口,其实,Entry也是一个接口,它是Map的子接口中的一个内部接口,就相当于是类中有内部类一样。为何要定义在其内部呢?
原因:a、Map集合中村的是映射关系这样的两个数据,是先有Map这个集合,才可有映射关系的存在,而且此类关系是集合的内部事务。
b、并且这个映射关系可以直接访问Map集合中的内部成员,所以定义在内部。

五.应用示例

示例1:
获取该字符串中的字母出现的次数,如:”sjokafjoilnvoaxllvkasjdfns”;希望打印的结果是:a(3)c(0)…..
通过结果发现,每个字母都有对应的次数,说明字母和次数之间有映射关系。代码如下:

/*
思路:1、将字符串转换为字符数组
      2、定义一个TreeMap集合,用于存储字母和字母出现的次数
      3、用数组去遍历集合,如果集合中有该字母则次数加1,如果集合中没有则存入
      4、将TreeMap集合中的元素转换为字符串
*/
package TreeMapTest;
import java.util.*;

class CharCount
{
    public static void main(String[] args) 
    {
        String s="sdfgzxcvasdfxcvdf";
        System.out.println("s中各字母出现的次数:"+charCount(s));
    }

    //定义一个方法获取字符串中字母出现的次数
    public static String charCount(String str)
    {
        char[] cha=str.toCharArray();//转换为字符数组

        //定义一个TreeMap集合,因为TreeMap集合会给键自动排序
        TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();

        int count=0;//定义计数变量
        for (int x=0;x<cha.length ;x++ )
        {
            if(!(cha[x]>='a'&&cha[x]<='z'||cha[x]>='A'&&cha[x]<='Z'))
                continue;//如果字符串中非字母,则不计数
            Integer value=tm.get(cha[x]);//获取集合中的值
            if(value!=null)//如果集合中没有该字母,则存入
                count=value;
            count++;
            tm.put(cha[x],count);//存入键值对
            count=0;//复位计数变量
        }

         StringBuilder sb=new StringBuilder();//定义一个容器

        //遍历集合,取出并以题目格式存入容器中
        for(Iterator<Character> it=tm.keySet().iterator();it.hasNext();)
        {
            Character ch=it.next();
            Integer value=tm.get(ch);
            sb.append(ch+"("+value+")");
        }
        return sb.toString();//返回字符串     
    }
}

示例2:在很多项目中,应用比较多的是一对多的映射关系,这就可以通过嵌套的形式将多个映射定义到一个大的集合中,并将大的集合分级处理,形成一个体系。

/*
map扩展知识。
map集合被使用是因为具备映射关系。
以下是班级对应学生,而学生中学号对应着姓名的映射关系:
"yureban"   Student("01" "zhangsan");

"yureban" Student("02" "lisi");

"jiuyeban" "01" "wangwu";
"jiuyeban" "02" "zhaoliu";

就如同一个学校有多个教室。每一个教室都有名称。
*/
import java.util.*;

class  MapExpandKnow
{
    public static void main(String[] args) 
    {
        //预热班集合
        HashMap<String,String> yureban=new HashMap<String,String>();
        //就业班集合
        HashMap<String,String> jiuyeban=new HashMap<String,String>();
        //学校集合
HashMap<String,HashMap<String,String>> czbk=new HashMap<String,HashMap<String,String>>();

        //学校中班级集合和名称的映射
        czbk.put("yureban",yureban);
        czbk.put("jiuyueban",jiuyeban);

//预热班级中学号与姓名的映射
        yureban.put("01","zhangsan");
        yureban.put("02","lisi");

        //就业班级中学号与姓名的映射
        jiuyeban.put("01","wangwu");
        jiuyeban.put("02","zhouqi");

            //直接显示全部学生信息
        getAllStudentInfo(czbk);

    }
    //定义一个方法获取全部学生信息,包括在哪个班级,叫什么名字,学号多少
    public static void getAllStudentInfo(HashMap<String ,HashMap<String,String>> hm)
    {
        for (Iterator<String> it=hm.keySet().iterator();it.hasNext() ; )//用keySet取出方式
        {
            String s= it.next();//班级名称
            System.out.println(s+":");
            HashMap<String,String> stu=hm.get(s);//班级集合

            getStudentInfo(stu);
        }
    }

    //获取班级中学生的信息,包括姓名和学号
    public static void getStudentInfo(HashMap<String,String> hm)
    {
        for (Iterator<String> it=hm.keySet().iterator();it.hasNext() ; )
        {
            String key=it.next();//学号
            String value=hm.get(key);//姓名
            System.out.println(key+"..."+value);
        }
    }
}

本文借鉴了
http://blog.csdn.net/kangmiao89757/article/category/1566771

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值