Java 中 Map 的使用
一、Map 概述
在Java 中 Map 将键映射到值的对象,一个映射不能包含重复的键,每个键最多只能映射到一个值,Map 接口和 Collection 接口的不同,Map 是双列的,Collection 是单列的,Map 的键唯一,Collection 的子体系 Set 是唯一的,Map 集合的数据结构针对键有效,跟值无关;Collection 集合的数据结构是针对元素有效。
LinkedHashMap与TreeMap
LinkedHashMap的底层的数据结构是链表和哈希表,元素有序,并且唯一元素的有序性由链表数据结构保证,唯一性由哈希表数据结构保证。Map集合的数据结构只和键有关。
TreeMap 不允许插入 null 键,键的数据结构是红黑树,可保证键的排序和唯一性,排序分为自然排序和比较器排序,线程是不安全的效率比较高。TreeMap 集合排序可通过实现 Comparable 接口,重写 CompareTo 方法;或者使用比较器。
二、实例
1、Map集合的遍历
方法一:使用迭代器遍历
public class Test {
public static void main(String[] args) {
HashMap<Phone,String> map = new HashMap<>();
map.put(new Phone("Apple",7000),"美国");
map.put(new Phone("Sony",5000),"日本");
map.put(new Phone("Huawei",6000),"中国");
Set<Phone> phones = map.keySet();
Iterator<Phone> iterator = phones.iterator();
while (iterator.hasNext()){
Phone next = iterator.next();
System.out.println(next.getBrand()+"=="+next.getPrice()+"=="+map.get(next));
}
}
}
class Phone{
private String Brand;
private int Price;
public Phone(String brand, int price) {
Brand = brand;
Price = price;
}
public String getBrand() {
return Brand;
}
public void setBrand(String brand) {
Brand = brand;
}
public int getPrice() {
return Price;
}
public void setPrice(int price) {
Price = price;
}
}
方法二:使用 entrySet 遍历
public class Test {
public static void main(String[] args) {
HashMap<Phone,String> map = new HashMap<>();
map.put(new Phone("Apple",7000),"美国");
map.put(new Phone("Sony",5000),"日本");
map.put(new Phone("Huawei",6000),"中国");
Set<Map.Entry<Phone, String>> entries = map.entrySet();
for (Map.Entry<Phone, String> entry : entries) {
System.out.println(entry.getKey().getBrand()+"==="+entry.getKey().getPrice()+"==="+entry.getValue());
}
}
}
一般来说建议使用 entrySet 遍历方式,其效率较高。
2、TreeMap集合的遍历
public class Test {
public static void main(String[] args) {
TreeMap<Phone,String> map = new TreeMap<>();
map.put(new Phone("Apple",7000),"美国");
map.put(new Phone("Sony",5000),"日本");
map.put(new Phone("Huawei",6000),"中国");
Set<Phone> phones = map.keySet();
Iterator<Phone> iterator = phones.iterator();
while(iterator.hasNext()){
Phone next = iterator.next();
System.out.println(next.getBrand()+"==="+next.getPrice()+"==="+map.get(next));
}
}
}
class Phone implements Comparable<Phone>{
private String Brand;
private int Price;
public Phone(String brand, int price) {
Brand = brand;
Price = price;
}
public String getBrand() {
return Brand;
}
public void setBrand(String brand) {
Brand = brand;
}
public int getPrice() {
return Price;
}
public void setPrice(int price) {
Price = price;
}
@Override
public int compareTo(Phone o) {
return this.getPrice() - o.getPrice();
}
}