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 HashMaphm1 = 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.iterator16 * */17 // 利用keySet()遍历18 Set 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()遍历,无法遍历key25 Collection 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 > entries = hm1.entrySet();33 System.out.println("entries= "+ entries); // [a=Customer:[Id=1, Name=AA],...]34 for(Map.Entry entry: entries){35 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());36 }37 38 // 利用entrySet().iterator()遍历39 Iterator > it = hm1.entrySet().iterator();40 while (it.hasNext()) {41 Map.Entry entry = it.next();42 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());43 }44 45 /*46 * HashMap常用方法示例47 * */48 // get49 Customer b = hm1.get("b");50 System.out.println(b); // Customer:[Id=2, Name=BB]51 52 // putIfAbsent, key值存在,不覆盖value53 hm1.putIfAbsent("e",new Customer(5,"EEE"));54 System.out.println(hm1);55 56 // containsKey57 boolean flag = hm1.containsKey("b");58 System.out.println(flag); // true59 60 // containsValue61 flag = hm1.containsValue(b);62 System.out.println(flag);63 64 // remove65 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); // false69 70 // replace71 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 // clone78 HashMap hm2 = (HashMap )hm1.clone();79 System.out.println(hm2);80 // clear81 hm2.clear();82 System.out.println(hm2); // {}83 System.out.println(hm1);84 // isEmpty85 flag = hm2.isEmpty();86 System.out.println(flag); // true87 // size88 int size = hm1.size();89 System.out.println(size); // 490 91 }92 }
Customer.java
1 import java.util.Objects; 2 3 public class Customer implements Comparable{ 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 @Override21 public String toString() {22 return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";23 }24 25 /*26 * 重写compareTo方法27 * 按Id或者name排序28 * 可以对整体添加负号决定升降序29 * */30 @Override31 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 @Override41 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 @Override50 public int hashCode() {51 return Objects.hash(customerId, customerName);52 }53 54 }
CustomerComparator.java
1 import java.util.Comparator; 2 3 public class CustomerComparator implements Comparator{ 4 5 @Override 6 public int compare(Customer c1, Customer c2) { 7 // 按Id排序 8 return c1.getCustomerId() - c2.getCustomerId(); 9 }10 }
!!!