Java容器——Map接口

本文详细介绍了 Java 中 HashMap 数据结构的基本概念、常用实现类、方法及其使用示例,包括键值对的存储、查找、遍历、修改等操作,并通过代码展示了如何在实际场景中应用 HashMap。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.定义

Map用于保存存在映射关系<key, value>的数据。其中key值不能重复(使用equals()方法比较),value值可以重复。

2.常用实现类

HashMap:和HashSet类似,键按键的HashCode()方法确定存储位置,无序

TreeMap:用于对键进行排序,方式与TreeSet相同

LinkedHashMap:和LinkedHashSet类似

3.方法

3.1 HashMap常用方法

void clear():移除所有映射

Object clone():浅拷贝原映射

boolean containsKey(Object key):判断是否包含指定键

boolean containsValue(Object value):判断是否包含指定值

Set<Map.Entry<K,V>> entrySet():返回包含映射关系的set集合

V get(Object key):查找给定键的值

boolean isEmpty():判断是否为空

Set<K> keySet():返回map中键的set集合

V put(K key, V value):存入键值对

V putIfAbsent(K key, V value):存入键值对,如果该键未存在map中

V remove(Object key):移除给定键的键值对

boolean remove(Object key, Object value):移除给定的键值对

V replace(K key, V value):替换给定键的值

boolean replace(K key, V oldValue, V newValue):如果键值对符合要求,替换新值

int size():返回键值对数目

Collection<V> values():返回value集合

注:Map接口没有继承Iterable接口,所以不能直接通过map.iterator进行遍历(List,Map拥有该接口,可以直接遍历),需要先转化为set类型,使用entrySet()方法,Map.Entry<k,v>中含有方法getKey()和getValue(),获取对应的键和值。

4.示例

MapFunc.java

 1 import java.util.*;
 2 
 3 public class MapFunc {
 4     public static void main(String[] args) {
 5 
 6         HashMap<String, Customer> hm1 = new HashMap<>();
 7         hm1.put("a", new Customer(1,"AA"));
 8         hm1.put("b", new Customer(2,"BB"));
 9         hm1.put("c", new Customer(3,"CC"));
10         hm1.put("d", new Customer(4,"DD"));
11         hm1.put("e", new Customer(5,"EE"));
12 
13         /*
14         * Map的几种遍历方法
15         * keySet、values、entrySet、entrySet.iterator
16         * */
17         // 利用keySet()遍历
18         Set<String> keys = hm1.keySet();
19         System.out.println("keys= "+ keys);  // [a, b, c, d]
20         for(String key: keys){
21             System.out.println("key= "+ key + " and value= " + hm1.get(key));
22         }
23 
24         // 利用values()遍历,无法遍历key
25         Collection<Customer> values = hm1.values();
26         System.out.println("values= "+ values);   // [Customer:[Id=1, Name=AA],...]
27         for(Customer cus: values){
28             System.out.println("value= " + cus);
29         }
30 
31         // 利用entrySet遍历
32         Set<Map.Entry<String,Customer>> entries = hm1.entrySet();
33         System.out.println("entries= "+ entries);    // [a=Customer:[Id=1, Name=AA],...]
34         for(Map.Entry<String, Customer> entry: entries){
35             System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
36         }
37 
38         // 利用entrySet().iterator()遍历
39         Iterator<Map.Entry<String, Customer>> it = hm1.entrySet().iterator();
40         while (it.hasNext()) {
41             Map.Entry<String, Customer> entry = it.next();
42             System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
43         }
44 
45         /*
46         * HashMap常用方法示例
47         * */
48         // get
49         Customer b = hm1.get("b");
50         System.out.println(b);      // Customer:[Id=2, Name=BB]
51 
52         // putIfAbsent, key值存在,不覆盖value
53         hm1.putIfAbsent("e",new Customer(5,"EEE"));
54         System.out.println(hm1);
55 
56         // containsKey
57         boolean flag = hm1.containsKey("b");
58         System.out.println(flag);     // true
59 
60         // containsValue
61         flag = hm1.containsValue(b);
62         System.out.println(flag);
63 
64         // remove
65         hm1.remove("c");
66         System.out.println(hm1);             // Customer:[Id=3, Name=CC]
67         flag = hm1.remove("b", new Customer(1,"BB"));
68         System.out.println(flag);         // false
69 
70         // replace
71         hm1.replace("b", new Customer(2,"BBB"));
72         System.out.println(hm1);
73         hm1.replace("d",new Customer(4,"D"),
74                 new Customer(4,"DDD"));    // 注意!!!
75         System.out.println(hm1);
76 
77         // clone
78         HashMap<String, Customer> hm2 = (HashMap<String, Customer>)hm1.clone();
79         System.out.println(hm2);
80         // clear
81         hm2.clear();
82         System.out.println(hm2);     // {}
83         System.out.println(hm1);
84         // isEmpty
85         flag = hm2.isEmpty();
86         System.out.println(flag);   // true
87         // size
88         int size = hm1.size();
89         System.out.println(size);   // 4
90 
91     }
92 }
View Code

Customer.java

 1 import java.util.Objects;
 2 
 3 public class Customer implements Comparable<Customer>{
 4 
 5     private int customerId;
 6     private String customerName;
 7 
 8     public Customer(Integer customerId, String customerName) {
 9         this.customerId = customerId;
10         this.customerName = customerName;
11     }
12 
13     public int getCustomerId() {
14         return customerId;
15     }
16     public String getCustomerName() {
17         return customerName;
18     }
19 
20     @Override
21     public String toString() {
22         return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";
23     }
24 
25      /*
26      * 重写compareTo方法
27      * 按Id或者name排序
28      * 可以对整体添加负号决定升降序
29      * */
30     @Override
31     public int compareTo(Customer o) {
32 //        return this.customerId - o.customerId;
33         return this.customerName.compareTo(o.customerName);
34     }
35 
36     /*
37     * 重写equals和hashcode方法
38     * 这里id和name相同则为同一对象
39     * */
40     @Override
41     public boolean equals(Object o) {
42         if (this == o) return true;
43         if (!(o instanceof Customer)) return false;
44         Customer customer = (Customer) o;
45         return customerId == customer.customerId &&
46                 Objects.equals(customerName, customer.customerName);
47     }
48 
49     @Override
50     public int hashCode() {
51         return Objects.hash(customerId, customerName);
52     }
53 
54 }
View Code

CustomerComparator.java

 1 import java.util.Comparator;
 2 
 3 public class CustomerComparator implements Comparator<Customer> {
 4 
 5     @Override
 6     public int compare(Customer c1, Customer c2) {
 7         // 按Id排序
 8         return c1.getCustomerId() - c2.getCustomerId();
 9      }
10 }
View Code

!!!

 

转载于:https://www.cnblogs.com/jfl-xx/p/4707319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值