黑马程序员_Java基础_集合框架成员Map

一, Map 接口不是 Collection 的子接口,但 Map 集合也是集合框架中的一员。

二,Map集合中我们重点要掌握HashMapHashTableTreeMap这三个分类,以及它们的区别,以及各自的应用领域。

 

Map接口的方法分类主要有:

1,判断:

containsKey(Object key)

containsValue(Object value)

isEmpty()

equals(Object obj)

 

2,获取:

get(Object key) 返回键所对应的值

size() 获取键值映射关系数

remove(Object key) 移除键对应的映射关系,返回键对应的值

put(K key,V value) 相集合中添加键值映射关系

values() 返回此映射中包含的值的Collection视图

keySet() 返回映射中包含键的Set视图

entrySet() 返回映射中包含的映射关系的Set视图

 

3,移除:

clear() 清空集合中的键值对

remove(Object key)

 

4,添加:

put(K key,V vlaue) Map集合中添加键值对

Map集合几种常用子类的比较:

|--Hashtable:底层是哈希表数据结构,不可以存入Null值和null键。线程同步,jdk1.0出现的。

 

|--HashMap:底层是哈希表数据结构,可以存入null值和null键。线程不同步,jdk1.2出现的,效率比HashTable高。

 

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

 

面试小技巧:注意面试中可能会问到HashMapHashTable的不同点,不能只回答线程同步问题,还要回答出HashTable不允许存null键和null值,但是HashMap可以存null键和null值。

 

扩展:其实Set集合的底层就是Map集合,Set集合是只有键的Map集合。

 

HashMap集合的入门示例:


import java.util.*;
public class MapDemo
{
    public static void main(String[] args) {
        Map<String,String> m = new HashMap<String,String>();
        m.put("001","zhangsan1");
        m.put("002","zhangsan2");
        m.put("003","zhangsan3");
        System.out.println(m.put("004","zhangsan4"));
        System.out.println(m.put("004","zhangsan4555"));
        //当添加相同的键不同的值时,后添加进来的键所对应的值会覆盖旧值,如果没有旧值,则返回空;
        System.out.println(m);
        System.out.println(m.remove(null));//要移除的键为空值时返回空;
        System.out.println(m.remove("002"));//移除键的同时,会返回键所对应的值;
        m.put("006",null);//HashMap集合可以将值或键设置为空,然后通过get方法获取键,这点和HashTable不同。
        System.out.println("-------" + m.get("006"));
        //通过get方法判断指定的键所对应的值是否存在;
        System.out.println("+++++" + m.containsKey("004"));
        Collection<String> coll = m.values();//获取m集合中的所有的值;
        System.out.println(coll);
        System.out.println(m);
    }
}

三,Map集合取出键与值得两种方法:

我们知道如何通过键获取对应的值,就是使用get(Object key)方法获取,但是这样毕竟只能获取单个的键对应的值,如果我们想获取所有的键对应的值,就需要通过循环取出才行。

这两种遍历元素的方式是:

1,对Map集合采用ketSet()方法,获取Map集合键所对应的Set视图,Set集合中有迭代器,可以遍历键,对键采用map集合中的get方法获得键对应的值。

2,通过Map.Entry方法获得Map中键值的映射关系,将关系作为元素存储到Set集合中,Map.Entry<K,V>接口中存在获取映射关系键和值得方法。

 

下面的示例代码给出类两种遍历Map集合中的所有元素的两种方法:

import java.util.*;
public class MapDemo2
{
    public static void main(String[] args) {
        Map<String,String> m = new HashMap<>();
        m.put("1","zhangsan01");
        m.put("2","zhangsan02");
        m.put("3","zhangsan03");
        //方式一:
        Set<String> hs= m.keySet();//获取Map集合的键的视图,是一个Set集合
        Iterator<String> it = hs.iterator();
        while (it.hasNext())
        {
            String key = it.next();
            String value = m.get(key);//通过键获取对应的值
            System.out.println(key + "---" + value);
        }
        //方式二:
        Set<Map.Entry<String,String>> et= m.entrySet();//获取Map集合的映射关系视图,是一个Set集合
        Iterator<Map.Entry<String,String>> it = et.iterator();//遍历Set集合中的元素,该元素是Map.Entry类型的
        while (it.hasNext())
        {
            Map.Entry<String,String> me= it.next();
            String k = me.getKey();//获取键
            String v = me.getValue();//获取值
            System.out.println(k + "-----" + v);
        }
    }
}

Map.Entry 接口的原理:其实 Entry 也是一个接口,它是在 Map 接口内部的一个接口,内部实现原理是:


interface Map
{
    public static interface Entry
    {
        public abstract Object getKey();
        public abstract Object getValue();
    }
}
class HashMap implements Map
{
    class Hash implements Map.Entry
    {
        public Object getKey() {}
        public Object getValue() {}
    }
}

Map集合的应用举例:

 

需求一:对学生对象的年龄进行升序排序;学生类包含姓名,年龄的属性,还要经学生的地址也进行存储。

 

分析:因为数据是可以以键值的形式存在吗,所以将学生对象作为键,将学生的地址作为值存储到Map集合中。因为还要对学生按照年龄排序,所以使用可以排序的Map集合TreeMap


import java.util.*;
//定义学生类,让学生类实现Comparable接口,以具备自定义的比较性
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;
    }
    //重写toString()方法可以通过直接打印学生对象就可以输出学生的姓名,年龄。
    public String toString() {
        return name + "---" + age;
    }
    //重写学生的hashCode方法
    public int hashCode() {
        return name.hashCode() + age*34;
    }
    //重写equals()方法
    public boolean equals(Object obj) {
        if(!(obj instanceof Student))
            return false;
        Student stu = (Student) obj;
        return this.name.equals(stu.name) && this.age==stu.age;
    }
    //重写compareTo方法是学生自身具备比较性
    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;
    }
}
//定义一个比较器,将该比较器作为参数传递给TreeMap集合,让集合自身具备比较性
class myComp implements Comparator<Student>
{
    public int compare(Student s1,Student s2) {
        int num = s1.getName().compareTo(s2.getName());
        if (num==0)
            return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
        return num;
    }
}
public class MapDemo4
{
    public static void main(String[] args) {
        Map<Student,String> tm = new TreeMap<>(new myComp());
        tm.put(new Student("zhangsan1",21),"beijing");
        tm.put(new Student("zhangsan5",25),"shanghai");
        tm.put(new Student("zhangsan6",29),"guangzhou");
        System.out.println(tm);
        
        //方法一:用keySet方法,先将集合的键取出存入到Set集合中,采用迭代器遍历每一个键并取出
        //循环取出键的时候引用Map集合中的get方法,(作用是从Map集合中取出相应键所对应的值,而
        //不是从迭代器和键所存在的集合中取);
        Set<Student> st = tm.keySet();
        Iterator<Student> it = st.iterator();
        while(it.hasNext()) {
            Student s =it.next();
            String add = tm.get(s);
            System.out.println(s + "====="  + add);
        }
        
        System.out.println("**********************************");
        //方法二:将Map集合引用entrySet方法存入到集合Set<Map.Entry<K,V>>中,对该Set的对象生成一个迭代器,该迭代器的
        //泛型类型是Map.Entry<K,V>,迭代过程中next()遍历的元素是Map.Entry<K,V>类型,它有两个特殊的获取对应映射关系的
        //键和值,就是getKey和getValue。
        Set<Map.Entry<Student,String>> st2 = tm.entrySet();
        Iterator <Map.Entry<Student,String>> it2 = st2.iterator();
        while (it2.hasNext())
        {
            Map.Entry<Student,String> entryMap = it2.next();
            System.out.println(entryMap.getKey() + "++++++++" + entryMap.getValue());
        }
    }
}

需求二:"sghkjhskhkjdkhjd"获取该字母出现的次数;希望打印结果为:a(1) c(2) ....的形式;

 

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

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

 

思路:

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

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

3,遍历数组。

将每一个字母作为键去查询map集合;如果返回的是null,将该字母和1存入到集合中。

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

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


import java.util.*;
public class MapTest
{
    public static void main(String[] args) {
        System.out.println(countDemo("sdgasagrdsaas"));
    }
    public static String countDemo(String st) {
        //将字符串转换成字符数组
        char[] arr = st.toCharArray();
        //定义一个临时存储字符和字符个数的有映射关系集合
        TreeMap<Character,Integer> ts = new TreeMap<>();
        int count = 0;//计数器,统计同一个键出现的次数
        for (int i = 0;i<arr.length ;i++ )
        {
            //如果字符串中出现不是字母的情况,比如空格,则跳出本次循环
            if (!(arr[i] >= 'a' && arr[i] <= 'z' || arr[i] >= 'A' && arr[i] <= 'Z'))
                continue;
            Integer n = ts.get(arr[i]);
            if(n != null)
                count = n;
            count++;
            ts.put(arr[i],count);
            count = 0;
        }
        //定义一个StringBuilder容器,存储需求中的格式
        StringBuilder sb = new StringBuilder();
        //遍历获取所有键值对
        Set<Map.Entry<Character,Integer>> sm = ts.entrySet();
        Iterator<Map.Entry<Character,Integer>> it = sm.iterator();
        while (it.hasNext())
        {
            Map.Entry<Character,Integer> em = it.next();
            Character key = em.getKey();
            Integer val = em.getValue();
            sb.append(key + "(" + val + ")");
        }
        return sb.toString();
    }
}

使用Map集合存储下图所示关系:

东湖学院:-->HashMap<String,ArrayList>("Room",ArrayList<Student>())

    |--学生寝室 stuRoom

        |--不同的学生 Student对象

            |--学生01

            |--学生02

    |--教师寝室 terRoom

        |--不同的老师 Teacher对象

            |--老师01

            |--老师02

 

 

需求三:定义一个Person类,包含姓名,编号属性。学生类和老师类都继承Person类。每个老师又拥有老师的寝室,

学生又拥有学生的寝室,将寝室作为键,学生和老师类作为值存储到一个Map集合。

 

分析:这里我们发现学生和老师是两种不同的对象,一开始我们想到的是将寝室字符串作为键,将老师或学生对象作为值

存储到Map集合,但是这样似乎行不通。因为学生类和老师类都是继承Person类的,我们可以将这类对象也存储到一个ArrayList

集合中,通过泛型限定我们知道,ArrayList集合中可以存储Person类或其子类,而这里刚好满足我们的要求。所以只要将

List 集合定义成存储 Person 及其子类就可以存储 Student 对象和 Teacher 对象。具体实现过程如下:  


import java.util.*;
public class MapDemo5
{
    public static void main(String[] args) {
        //HashMap集合存储的键是字符串类型的寝室分类,对应的值是ArrayList集合,可以存储Person及其子类类型
        HashMap<String,ArrayList<? extends Person>> wdh = new HashMap<>();
        //定义ArrayList,存储学生类类型和老师类类型
        ArrayList<Student> stu = new ArrayList<>();
        ArrayList<Teacher> ter = new ArrayList<>();
        //向Map集合添加元素
        wdh.put("stuRoom",stu);
        wdh.put("terRoom",ter);
        //向学生ArrayList中添加元素,是学生对象
        stu.add(new Student("zhangsan1",23));
        stu.add(new Student("zhangsan3",25));
        stu.add(new Student("zhangsan54",27));
        //向老师ArrayList中添加元素,是老师对象
        ter.add(new Teacher("mr wang",001));
        ter.add(new Teacher("mr zhang",003));
        //遍历Map集合中的所有元素
        Set<String> se = wdh.keySet();
        Iterator<String> it = se.iterator();
        while (it.hasNext())
        {
            String s = it.next();
            ArrayList<? extends Person> st = wdh.get(s);
            System.out.println(s);
            //遍历List集合中的所有元素,并输出
            Iterator<? extends Person> it1 = st.iterator();
            while (it1.hasNext())
            {
                System.out.println(it1.next());
            }
        }
    }
}
class Person
{
    private String name;
    private int num;
    Person(String name,int num) {
        this.name = name;
        this.num = num;
    }
    public String getName() {
        return name;
    }
    public int getNum() {
        return num;
    }
    public String toString() {
        return name + "::" + num;
    }
}
class Student extends Person
{
    Student(String name,int num) {
        super(name,num);
    }
}
class Teacher extends Person
{
    Teacher(String name,int num) {
        super(name,num);
    }
}

东湖学院:-->HashMap<String,HashMap>("Room",HashMap<String,Integer>(stu01,stu02))

    |--学生寝室stuRoom -->HashMap<String,Integer>(stu01,01)

        |--不同的学生

            |--学生01

            |--学生02

    |--教师寝室terRoom -->HashMap<String,Integer>(ter01,02)

        |--不同的老师

            |--老师01

            |--老师02

 

分析:如果不将学生封装成一个单独的类,我们发现,不管是老师类还是学生类,他们的属性都是集成自 Person 的姓名和编号,姓名都是 String 类型,编号都是 Integer 类型,所以我们将学生和老师的信息也一键值的形式存储到 Map 集合中,在将这个 Map 集合作为值,将老师或学生的地址做为键存储到 Map 集合中。  


import java.util.*;
public class MapTest2
{
    public static void main(String[] args) {
        //定义一个HashMap集合,键是String类型的地址,值是HashMap类型的映射关系
        HashMap<String,HashMap<String,Integer>> wdh = new HashMap<>();
        //键类型的HashMap,它的键是String类型的姓名,值是Integer类型的编号
        HashMap<String,Integer> rooms = new HashMap<>();
        HashMap<String,Integer> roomt = new HashMap<>();
        
        //将映射关系存储到Map集合
        wdh.put("stuRoom",rooms);
        wdh.put("terRoom",roomt);
        
        rooms.put("stu01",001);
        rooms.put("stu02",002);
        rooms.put("stu03",003);
        roomt.put("ter01",001);
        roomt.put("ter02",002);
        
        //打印输出结果
        roomInfo(wdh);
    }
    
    public static void roomInfo(HashMap<String,HashMap<String,Integer>> ww) {
        //获取键值映射关系视图,是一个Set集合
        Set<Map.Entry<String,HashMap<String,Integer>>> se = ww.entrySet();
        //使用迭代器迭代出Map集合的值
        Iterator<Map.Entry<String,HashMap<String,Integer>>> it = se.iterator();
        while (it.hasNext())
        {
            Map.Entry<String,HashMap<String,Integer>> me = it.next();
            String roo = me.getKey();
            //通过键值映射视图获取值,该值也是一个Map集合
            HashMap<String,Integer> hm = me.getValue();
            System.out.println(roo);
            //将获取的内部Map集合传递给info方法,获取详细信息
            info(hm);
            //如果把info方法中的代码放入此处,则是循环套循环,分开成不同方法可读性更好;
        }
    }
    public static void info(HashMap<String,Integer> room) {
        //StringBuilder sb = new StringBuilder();
        //迭代获取:键———>老师或学生姓名,值———>学生或老师编号
        Set<String> s = room.keySet();
        Iterator<String> it = s.iterator();
        while (it.hasNext())
        {
            String ss= it.next();
            Integer in = room.get(ss);
            System.out.println(ss + "-----" + in);
        }
        //return sb.toString();
    }
}









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值