博客
关于我
Java进阶:Map集合
阅读量:263 次
发布时间:2019-03-01

本文共 4841 字,大约阅读时间需要 16 分钟。

Java Map集合详解

1. 概述

在现实生活中,我们经常会看到如IP地址与主机名、身份证号与个人等一一对应的映射关系。Java为此提供了专门的集合类——java.util.Map接口,用以存储这种键值对的对象。

通过查看Map接口描述,可以发现其与Collection接口的主要区别在于存储形式。Collection中的集合元素是孤立存在的,而Map中的集合元素则是成对存在的,每个元素由键与值两部分组成,通过键可以定位对应的值。Collection称为单列集合,Map称为双列集合。需要注意的是,Map集合的键不能重复,但值可以重复,每个键只能对应一个值。


2. Map常用子类

2.1 HashMap<K,V>

HashMap是最常用的Map实现类,其内部采用哈希表结构存储数据。由于哈希表的特点,HashMap的性能非常高,插入、删除和查找操作均为O(1)时间复杂度。为了保证键的唯一性,HashMap要求键必须重写hashCode()equals()方法。

2.2 LinkedHashMap<K,V>

LinkedHashMapHashMap的一个子类,其内部不仅采用了哈希表结构,还引入了链表结构。链表用于存储键的顺序信息,使得LinkedHashMap能够保持元素的插入顺序。因此,LinkedHashMap既保证了高效的查找性能,又保留了元素的顺序,适用于需要有序存储键值对的场景。


3. Map接口常用方法

3.1 基本操作方法

  • public V put(K key, V value):将指定键与值添加到集合中。
  • public V remove(Object key):删除指定键所对应的键值对,返回被删除的值。
  • public V get(Object key):根据键获取对应的值。
  • boolean containsKey(Object key):判断集合中是否包含指定键。
  • public Set<K> keySet():获取集合中所有键,返回一个Set集合。
  • public Set<Map.Entry<K,V>> entrySet():获取集合中所有键值对对象,返回一个Set集合。

3.2 方法演示

public class MapDemo {    public static void main(String[] args) {        Map
map = new HashMap<>(); map.put("黄晓明", "杨颖"); map.put("文章", "马伊琍"); map.put("邓超", "孙俪"); System.out.println(map); System.out.println(map.remove("邓超")); System.out.println(map); System.out.println(map.get("黄晓明")); System.out.println(map.get("邓超")); }}

4. Map集合的遍历方式

4.1 键找值方式

  • 获取所有键:Set<K> keys = map.keySet();
  • 遍历每个键:for (K key : keys) { ... }
  • 获取对应的值:String value = map.get(key);
  • 示例代码:

    public class MapDemo01 {    public static void main(String[] args) {        Map
    map = new HashMap<>(); map.put("胡歌", "霍建华"); map.put("郭德纲", "于谦"); map.put("薛之谦", "大张伟"); Set
    keys = map.keySet(); for (String key : keys) { String value = map.get(key); System.out.println(key + "的CP是:" + value); } }}

    4.2 Entry键值对对象

    Map集合中的每个键值对可以看作是一个Entry对象。Entry类提供了获取键和值的方法:

    • public K getKey():获取键。
    • public V getValue():获取值。

    获取所有Entry对象的方法:Set<Map.Entry<K,V>> entrySet = map.entrySet();

    示例代码:

    public class MapDemo02 {    public static void main(String[] args) {        Map
    map = new HashMap<>(); map.put("胡歌", "霍建华"); map.put("郭德纲", "于谦"); map.put("薛之谦", "大张伟"); Set
    > entrySet = map.entrySet(); for (Map.Entry
    entry : entrySet) { System.out.println(entry.getKey() + "的CP是:" + entry.getValue()); } }}

    5. 存储自定义类型键值

    在实际应用中,除了简单的字符串键值对,Map集合还可以存储自定义对象。例如,可以将学生对象作为键,家庭住址作为值。

    5.1 编写学生类

    public class Student {    private String name;    private int age;    public Student(String name, int age) {        this.name = name;        this.age = age;    }    @Override    public boolean equals(Object o) {        if (this == o)            return true;        if (o == null || getClass() != o.getClass())            return false;        Student student = (Student) o;        return age == student.age && Objects.equals(name, student.name);    }    @Override    public int hashCode() {        return Objects.hash(name, age);    }}

    5.2 测试类

    public class HashMapTest {    public static void main(String[] args) {        Map
    map = new HashMap<>(); map.put(new Student("lisi", 28), "上海"); map.put(new Student("wangwu", 22), "北京"); map.put(new Student("zhaoliu", 24), "成都"); map.put(new Student("wangwu", 22), "南京"); Set
    keySet = map.keySet(); for (Student key : keySet) { String value = map.get(key); System.out.println(key.toString() + "....." + value); } }}

    6. LinkedHashMap存储顺序

    LinkedHashMap结合了哈希表和链表的优势,既保证了高效查找,又保留了元素的插入顺序。以下是LinkedHashMap的使用示例:

    public class LinkedHashMapDemo {    public static void main(String[] args) {        LinkedHashMap
    map = new LinkedHashMap<>(); map.put("邓超", "孙俪"); map.put("李晨", "范冰冰"); map.put("刘德华", "朱丽倩"); Set
    > entrySet = map.entrySet(); for (Map.Entry
    entry : entrySet) { System.out.println(entry.getKey() + " " + entry.getValue()); } }}

    7. Map集合练习:字符频率统计

    需求:统计一个字符串中每个字符的出现次数。

    实现步骤:

  • 创建HashMap集合,键为字符,值为出现次数。
  • 遍历字符串中的每个字符。
  • 判断字符是否存在于集合中:
    • 如果不存在,新增键,值设为1。
    • 如果存在,值加1并更新。
  • 打印最终结果。
  • 代码实现:

    public class MapTest {    public static void main(String[] args) {        System.out.println("请录入一个字符串:");        String line = new Scanner(System.in).nextLine();        findChar(line);    }    private static void findChar(String line) {        HashMap
    map = new HashMap<>(); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (!map.containsKey(c)) { map.put(c, 1); } else { Integer count = map.get(c); map.put(c, count + 1); } } System.out.println(map); }}

    转载地址:http://avux.baihongyu.com/

    你可能感兴趣的文章
    NSOperation基本操作
    查看>>
    NSRange 范围
    查看>>
    NSSet集合 无序的 不能重复的
    查看>>
    NSURLSession下载和断点续传
    查看>>
    NSUserdefault读书笔记
    查看>>
    NS图绘制工具推荐
    查看>>
    NT AUTHORITY\NETWORK SERVICE 权限问题
    查看>>
    NT symbols are incorrect, please fix symbols
    查看>>
    ntelliJ IDEA 报错:找不到包或者找不到符号
    查看>>
    NTFS文件权限管理实战
    查看>>
    ntko web firefox跨浏览器插件_深度比较:2019年6个最好的跨浏览器测试工具
    查看>>
    ntko文件存取错误_苹果推送 macOS 10.15.4:iCloud 云盘文件夹共享终于来了
    查看>>
    ntp server 用法小结
    查看>>
    ntpdate 通过外网同步时间
    查看>>
    ntpdate同步配置文件调整详解
    查看>>
    NTPD使用/etc/ntp.conf配置时钟同步详解
    查看>>
    NTP及Chrony时间同步服务设置
    查看>>
    NTP服务器
    查看>>
    NTP配置
    查看>>
    NUC1077 Humble Numbers【数学计算+打表】
    查看>>