Java容器——Map接口

时间:2021-12-04 06:39:08

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

 import java.util.*;

 public class MapFunc {
public static void main(String[] args) { HashMap<String, Customer> hm1 = new HashMap<>();
hm1.put("a", new Customer(1,"AA"));
hm1.put("b", new Customer(2,"BB"));
hm1.put("c", new Customer(3,"CC"));
hm1.put("d", new Customer(4,"DD"));
hm1.put("e", new Customer(5,"EE")); /*
* Map的几种遍历方法
* keySet、values、entrySet、entrySet.iterator
* */
// 利用keySet()遍历
Set<String> keys = hm1.keySet();
System.out.println("keys= "+ keys); // [a, b, c, d]
for(String key: keys){
System.out.println("key= "+ key + " and value= " + hm1.get(key));
} // 利用values()遍历,无法遍历key
Collection<Customer> values = hm1.values();
System.out.println("values= "+ values); // [Customer:[Id=1, Name=AA],...]
for(Customer cus: values){
System.out.println("value= " + cus);
} // 利用entrySet遍历
Set<Map.Entry<String,Customer>> entries = hm1.entrySet();
System.out.println("entries= "+ entries); // [a=Customer:[Id=1, Name=AA],...]
for(Map.Entry<String, Customer> entry: entries){
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
} // 利用entrySet().iterator()遍历
Iterator<Map.Entry<String, Customer>> it = hm1.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Customer> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
} /*
* HashMap常用方法示例
* */
// get
Customer b = hm1.get("b");
System.out.println(b); // Customer:[Id=2, Name=BB] // putIfAbsent, key值存在,不覆盖value
hm1.putIfAbsent("e",new Customer(5,"EEE"));
System.out.println(hm1); // containsKey
boolean flag = hm1.containsKey("b");
System.out.println(flag); // true // containsValue
flag = hm1.containsValue(b);
System.out.println(flag); // remove
hm1.remove("c");
System.out.println(hm1); // Customer:[Id=3, Name=CC]
flag = hm1.remove("b", new Customer(1,"BB"));
System.out.println(flag); // false // replace
hm1.replace("b", new Customer(2,"BBB"));
System.out.println(hm1);
hm1.replace("d",new Customer(4,"D"),
new Customer(4,"DDD")); // 注意!!!
System.out.println(hm1); // clone
HashMap<String, Customer> hm2 = (HashMap<String, Customer>)hm1.clone();
System.out.println(hm2);
// clear
hm2.clear();
System.out.println(hm2); // {}
System.out.println(hm1);
// isEmpty
flag = hm2.isEmpty();
System.out.println(flag); // true
// size
int size = hm1.size();
System.out.println(size); // }
}

Customer.java

 import java.util.Objects;

 public class Customer implements Comparable<Customer>{

     private int customerId;
private String customerName; public Customer(Integer customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
} public int getCustomerId() {
return customerId;
}
public String getCustomerName() {
return customerName;
} @Override
public String toString() {
return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";
} /*
* 重写compareTo方法
* 按Id或者name排序
* 可以对整体添加负号决定升降序
* */
@Override
public int compareTo(Customer o) {
// return this.customerId - o.customerId;
return this.customerName.compareTo(o.customerName);
} /*
* 重写equals和hashcode方法
* 这里id和name相同则为同一对象
* */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Customer)) return false;
Customer customer = (Customer) o;
return customerId == customer.customerId &&
Objects.equals(customerName, customer.customerName);
} @Override
public int hashCode() {
return Objects.hash(customerId, customerName);
} }

CustomerComparator.java

 import java.util.Comparator;

 public class CustomerComparator implements Comparator<Customer> {

     @Override
public int compare(Customer c1, Customer c2) {
// 按Id排序
return c1.getCustomerId() - c2.getCustomerId();
}
}

!!!