集合(Map接口)

在这里插入图片描述

Map接口和常用方法

特点(JDK8)

  • Map与Collection并列存在。用于保存具有映射关系的数据:Key-Value
  • Map中的key和value可以是任何引用类型的数据,会封装到HashMap$Node对象中
  • Map中的key不允许重复,原因和HashSet一样
  • Map中的Value可以重复
  • Map中的key可以为null,value可以为null,注意key为null,只能有一个,Value为null可以多个(注意key=“null"的情况
  • 常用String类作为Map的key
  • key和value之间存在单向一对一关系,即通过指定的key总能找到对应的value
Map map = new HashMap(); 
map.put("no1", "李四");//k-v 
map.put("no2", "张无忌");//k-v 
map.put("no1", "张三丰");//当有相同的 k , 就等价于替换. 
map.put("no3", "张三丰");//k-v 
map.put(null, null); //k-v 
map.put(null, "abc"); //等价替换 
map.put("no4", null); //k-v 
map.put("no5", null); //k-v 
map.put(1, "赵敏");//k-v 
map.put(new Object(), "金毛狮王");//k-v 
// 通过 get 方法,传入 key ,会返回对应的 value 
System.out.println(map.get("no2"));//张无忌 

Map接口常用方法

  • put(key,value)添加键值对
  • remove:根据键删除映射关系
  • get 根据键获取值
  • size获取元素个数
  • isEmpty() 判断个数是否为空
  • clear():清除k-v
  • containsKey查找键是否存在

Map接口遍历方法

  • ContainsKey:查找键是否存在
  • KeySet:获取所有的键
  • values:获取所有的值
  • entrySet获取所有的关系k-v

import java.util.*;

public class MapFor {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("邓超", "孙俪");
        map.put("王宝强", "马蓉");
        map.put("宋喆", "马蓉");
        map.put("刘令博", null);
        map.put(null, "刘亦菲");
        map.put("鹿晗", "关晓彤");
//第一组: 先取出 所有的 Key , 通过 Key 取出对应的 Value
        Set keyset = map.keySet();
//(1) 增强 for
        System.out.println("-----第一种方式-------");
        for (Object key : keyset) {
            System.out.println(key + "-" + map.get(key));
        }
//(2) 迭代器
        System.out.println("----第二种方式--------");
        Iterator iterator = keyset.iterator();
        while (iterator.hasNext()) {
            Object key = iterator.next();
            System.out.println(key + "-" + map.get(key));
        }


//第二组: 把所有的 values 取出
        Collection values = map.values();
//这里可以使用所有的 Collections 使用的遍历方法
//(1) 增强 for
        System.out.println("---取出所有的 value 增强 for----");
        for (Object value : values) {
            System.out.println(value);
        }
//(2) 迭代器
        System.out.println("---取出所有的 value 迭代器----");
        Iterator iterator2 = values.iterator();
        while (iterator2.hasNext()) {
            Object value = iterator2.next();
            System.out.println(value);
        }


        
//第三组: 通过 EntrySet 来获取 k-v
        Set entrySet = map.entrySet();// EntrySet<Map.Entry<K,V>>
//(1) 增强 for
        System.out.println("----使用 EntrySet 的 for 增强(第 3 种)----");
        for (Object entry : entrySet) {
//将 entry 转成 Map.Entry
            Map.Entry m = (Map.Entry) entry;
            System.out.println(m.getKey() + "-" + m.getValue());
        }
//(2) 迭代器
        System.out.println("----使用 EntrySet 的 迭代器(第 4 种)----");
        Iterator iterator3 = entrySet.iterator();
        while (iterator3.hasNext()) {
            Object entry = iterator3.next();
//System.out.println(next.getClass());//HashMap$Node -实现-> Map.Entry (getKey,getValue)
//向下转型 Map.Entry
            Map.Entry m = (Map.Entry) entry;
            System.out.println(m.getKey() + "-" + m.getValue());
        }

    }
}

HashMap

  • Map接口的常用实现类:HashMap、Hashtable和Properties
  • HashMap是Map接口使用频率最高的实现类
  • HashMap是以key-val对的方式来存储数据
  • key不能重复,但是值可以重复,允许使用null键和NULL值
  • 如果添加相同的key则会覆盖原来的k-v等同于修改k不会替换v会替换
  • 与HashSet一样,不会保证映射的顺序,因为底层以hash表的方式存储
  • HashMap没有实现同步,因此线程是不安全的,方法没有做同步互斥的操作没有synchronized

Hashtable

  • 存放的元素是键值对即k-v
  • 键和值都不能为null,否则或抛出NullPointException
  • hashTable的使用方法基本上和HashMap一样
  • hashTable的线程是安全的hashMap是线程不安全

Hashtable和HashMap对比

版本线程安全(同步)效率允许null键值
HashMap1.2不安全可以
Hashtable1.0安全较低不可以

Properties

  • Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存数据。
  • 他的使用特点和Hashtable类似
  • Properties 还可以用于从 xxx.properties 文件中,加载数据到Properties类对象,并进行读取和修改
  • xoxx.properties文件通常作为配置文件

TreeMap排序

  • TreeMap基于二叉树数据结构存储数据,同时实现了SortedMap接口以保障元素顺序存取,默认按照键的升序排序,也可以自定义排序比较器;

  • TreeMap常用于实现排序的映射列表,在使用TreeMap时其key必须实现Comparable接口或采用自定义的比较器,否则会抛出java.lang.ClassCastExption异常;

public class TreeMap_ {
    public static void main(String[] args) {
//使用默认的构造器,创建 TreeMap, 是无序的(也没有排序)
/*
要求:按照传入的 k(String) 的大小进行排序
*/

        //  TreeMap treeMap = new TreeMap();
        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
//按照传入的 k(String) 的大小进行排序
                //return ((String) o2).compareTo((String) o1);
//按照 K(String) 的长度大小排序
                return ((String) o2).length() - ((String) o1).length();
            }
        });
        treeMap.put("jack", "杰克");
        treeMap.put("tom", "汤姆");
        treeMap.put("kristina", "克瑞斯提诺");
        treeMap.put("smith", "斯密斯");
        treeMap.put("hpp", "杰克逊");//加入不了
        System.out.println("treemap=" + treeMap);
        //treemap={kristina=克瑞斯提诺, smith=斯密斯, jack=杰克, tom=杰克逊}
/*
解读源码:
1. 构造器. 把传入的实现了 Comparator 接口的匿名内部类(对象),传给给 TreeMap 的 comparator
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
2. 调用 put 方法
2.1 第一次添加, 把 k-v 封装到 Entry 对象,放入 root
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
2.2 以后添加
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do { //遍历所有的 key , 给当前 key 找到适当位置
parent = t;
cmp = cpr.compare(key, t.key);//动态绑定到我们的匿名内部类的 compare
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else //如果遍历过程中,发现准备添加 Key 和当前已有的 Key 相等,就不添加
return t.setValue(value);
} while (t != null);
}
*/
    }
}

key实现Comparable接口

public class StuTreeMap {
    public static void main(String[] args) {
        TreeMap<Student,String> treeMap = new TreeMap<>();
        treeMap.put(new Student("大哥",24),"大哥");
        treeMap.put(new Student("二哥",23),"二哥");
        treeMap.put(new Student("三哥",22),"三哥");
        treeMap.put(new Student("四哥",21),"四哥");
        Set<Student> studentSet = treeMap.keySet();
        for (Student student : studentSet) {
            System.out.println(student.toString());
        }
    }
}
// 这里就省略getter和setter方法了
class Student implements Comparable<Student>{
 
    private String name;
    private int age;
 
    public Student() {
    }
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
 
    @Override
    public int compareTo(Student o) {
        // 实现Comparable接口在这里也是自定义排序规则
        // 如果什么也不写,直接默认return 0的话,只能存储第一个被put的元素
        // 注意:升序就这么个写法,不要看网上其他的什么相等返回0,相等的话要返回this.age,否则会出问题
        if(age > o.age){
            return 1;
        }else if(age < o.age){
            return -1;
        }
        return this.age;
    }
}

采用自定义比较器

 public class StuTreeMap2 {
    public static void main(String[] args) {
        TreeMap<Student2,String> treeMap = new TreeMap<>(new Comparator<Student2>() {
            @Override
            public int compare(Student2 o1, Student2 o2) {
                // 基本和key实现Comparable接口,重写compareTo方法一致
                // 升序排序就是这么写的
                if(o1.getAge() > o2.getAge()){
                    return 1;
                }else if(o1.getAge() < o2.getAge()){
                    return -1;
                }
                // 相等的时候不能返回0
                return o1.getAge();
            }
        });
        treeMap.put(new Student2("大哥",24),"大哥");
        treeMap.put(new Student2("二哥",23),"二哥");
        treeMap.put(new Student2("三哥",22),"三哥");
        treeMap.put(new Student2("四哥",21),"四哥");
        Set<Student2> studentSet = treeMap.keySet();
        for (Student2 student : studentSet) {
            System.out.println(student.toString());
        }
    }
}
 
class Student2{
 
    private String name;
    private int age;
 
    public Student2() {
    }
 
    public Student2(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
//运行结果
Student{name='四哥', age=21}
Student{name='三哥', age=22}
Student{name='二哥', age=23}
Student{name='大哥', age=24}

两种方式区别不大,一个是key实现Comparable接口,重写compareTo()方法,另一个是在TreeMap的构造函数中创建new Comparator匿名内部类,重写compare 方法;两者实现的功能都是一样的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值