1. 程式人生 > 實用技巧 >Java基礎之:集合——Map

Java基礎之:集合——Map

Java基礎之:集合——Map

  1. Map與Collection並列存在。用於儲存具有對映關係的資料鍵值對:Key—Value

  2. 在Map中Key與Value都可以存放任何型別的資料。

  3. Key是用Set來存放的,不允許重複,允許有null但只能有一個。常用String類作為Map的“鍵”(key)

  4. Value是用Collection存放的,可以是Set也可以是List,所以當Value使用List時允許重複,且可以有多個null值。

  5. key與value之間存在單向一對一關係,即通過指定key總能找到唯一的確定的一個value。

  6. 因為key是用Set存放的,而value是通過key進行查詢返回的。所以Map是無序的。

底層結構圖:

虛線為實現關係,實線為繼承關係。

Map介面常用方法

  1. put:新增

  2. get:根據鍵獲取值

  3. size:獲取元素個數

  4. isEmpty:判斷個數是否為0

  5. containsKey:查詢鍵是否存在

  6. remove:根據鍵刪除對映關係

  7. clear:清除

package class_Map;
import java.util.HashMap;
import java.util.Map;
public class ClassTest01_MapMethods {
​
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) {
​
        Map map = new HashMap();
        
        //put:新增。
        /*
            1.若要新增的key值集合中沒有,則直接新增。
            2.若集合中已存在相同的key值,則直接替換掉。
            3.key中只能有一個null存在,若存在多個null則根據上面的規則,只會保留最後一個null
            4.value中可以有多個null存在。
            5.k-v是無序的,取出順序和新增順序是不一樣的。
         */
        map.put("1", "hello01");
        map.put("2", "hello02");
        map.put("3", "hello03");
        map.put("3", "hello05");
        map.put("4", "hello02");
        map.put(null, "hello02");
        map.put("5", null);
​
        //get:根據鍵獲取值
        System.out.println(map.get("3"));//返回值:hello05
        
        //size:獲取元素個數
        System.out.println(map.size());//返回值:6
        
        //isEmpty:判斷個數是否為0
        System.out.println(map.isEmpty()); //返回值:false
        
        //containsKey:查詢鍵是否存在
        System.out.println(map.containsKey(null)); //返回值:true
        
        //remove:根據鍵刪除對映關係,返回指為鍵所指的值
        System.out.println(map.remove(null)); //返回值:hello02
        
        //clear:清除
        map.clear();
        
        System.out.println(map);
    }
}

Map介面的遍歷方式

需要使用的方法:

  1. containsKey():查詢鍵是否存在

  2. keySet():獲取所有的鍵,返回一個Set集合

  3. entrySet():獲取所有關係,返回一個Set集合

  4. values():獲取所有的值,返回一個Collection集合

兩種遍歷方式(每種方式又分別有迭代器和增強for兩種):

  1. 遍歷鍵再通過鍵取出對應的值

  2. 直接遍歷整個鍵值對k-v

package class_Map;
​
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
​
public class ClassTest02_ForeachMap {
​
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
​
        Map map = new HashMap();
        
        map.put("1", "hello01");
        map.put("2", "hello02");
        map.put("3", "hello03");
        map.put("3", "hello05");
        map.put("4", "hello02");
        map.put(null, "hello02");
        map.put("5", null);
        
        //方式1:遍歷鍵,再取出值
        System.out.println("========方式一:迭代器=======");
        Set key = map.keySet(); //取出key,放入Set集合
        //迭代器方式:
        Iterator iterator = key.iterator();
        while(iterator.hasNext()) {
            Object obj = iterator.next();   //遍歷鍵,將鍵賦值給obj
            System.out.println(obj + " == " + map.get(obj)); //通過鍵,訪問值,進行遍歷
        }
        iterator = key.iterator();
        
        //增強for迴圈方式:
        System.out.println("========方式一:增強for=======");
        for(Object obj:key) {
            System.out.println(obj + " -- " + map.get(obj));
        }
        
        
        //方式二:直接遍歷鍵值對
        //將鍵值對放入Set中,此時entrySet編譯型別為Set集合,執行型別為HashMap$Node("$"符號代表內部類,後面跟類名是內部類,跟數值是匿名內部類)
        Set entrySet = map.entrySet();  //取出鍵值對k-v,放入Set集合
        
        //迭代器方式:
        System.out.println("========方式二:迭代器=======");
        Iterator iterator2 = entrySet.iterator();
        while(iterator2.hasNext()) {
            //這裡無法訪問HashMap.Node,但Node實現了Map介面中的一個內部介面Entry,可以使用動態繫結機制
//          HashMap.Node node = (HashMap.Node)iterator2.next(); //報錯:The type HashMap.Node is not visible
            /*
                理解為什麼需要是用Map.Entry來強轉從entrySet中取出的鍵值對:
                    1.在HashMap中有內部類Node,用於儲存鍵值對,但Node是靜態成員內部類,不可以在外部訪問,所以不能使用其get方法。
                    2.由於HashMap繼承與Map介面,Node又實現了Map介面中的一個內部介面Entry。
                    3.即通過Entry介面就可以通過動態繫結的方式訪問到Node內部類的方法
             */
            Map.Entry entry = (Map.Entry)iterator2.next();
            System.out.println(entry.getKey() + " :: " + entry.getValue());
        }
        iterator2 = entrySet.iterator();
        
        //增強for迴圈方式:
        System.out.println("========方式二:增強for=======");
        for(Object obj:entrySet) {
            Map.Entry entry = (Map.Entry)obj;
            System.out.println(entry.getKey() + " .. " + entry.getValue());
        }
    }
}

說明:直接遍歷鍵值對所使用的動態繫結機制的思路和"OOP——內部類"最後的思考題相同。

Map介面練習

使用HashMap新增3個員工物件,要求

鍵:員工id

值:員工物件

並遍歷顯示工資>18000的員工

(遍歷方式最少兩種)

員工類:姓名、工資、員工id

package class_Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ClassWork01 {
​
    @SuppressWarnings({ "unused", "rawtypes", "unchecked" })
    public static void main(String[] args) {
        Map hashMap = new HashMap();
        
        Employee employee1 = new Employee("小范", 1001, 22000);
        Employee employee2 = new Employee("小黃", 1002, 14000);
        Employee employee3 = new Employee("小雨", 1003, 23000);
        
        hashMap.put(employee1.getId(), employee1);  //這裡第一個引數employee1.getId()自動裝箱,因為原本需要是Object型別
        hashMap.put(employee2.getId(), employee2);  //而取出來是Int型別,自動裝箱為Integer。
        hashMap.put(employee3.getId(), employee3);
        
//      System.out.println(hashMap);
        
        //遍歷方式1:遍歷鍵,再通過鍵,取出值
        Set key = hashMap.keySet();
        Iterator iterator = key.iterator();
        while(iterator.hasNext()) {
            //將hashMap中的key鍵取出,放入Set中(實際是HashSet),再通過迭代器遍歷取出key,通過hashMap.get方法取出值
            Object obj = iterator.next();   //從HashSet中取出key鍵 , 此時key編譯型別是Object,執行型別是Integer(因為鍵是員工id)
//          System.out.println(obj.getClass());
            if(isOut(hashMap.get(obj))) {
                System.out.println(obj + "--" + hashMap.get(obj));
            }
        }
        iterator = key.iterator();
        
        System.out.println("=========================================");
        //遍歷方式2:直接遍歷鍵值對
        //將鍵值對放入Set中,此時entrySet編譯型別為Set介面,執行型別為HashMap$Node("$"符號代表內部類,後面跟類名是內部類,跟數值是匿名內部類)
        Set entrySet = hashMap.entrySet();  
        Iterator iterator2 = entrySet.iterator();
        while(iterator2.hasNext()) {
            /*
             *  理解為什麼需要是用Map.Entry來強轉從entrySet中取出的鍵值對
             *  1.在HashMap中有內部類Node,用於儲存鍵值對,但Node是靜態成員內部類,不可以在外部訪問,所以不能使用其get方法。
             *  2.由於HashMap繼承與Map介面,Node又實現了Map介面中的一個內部介面Entry。
             *  3.即通過Entry介面就可以通過動態繫結的方式訪問到Node內部類的方法
             */
            Map.Entry node = (Map.Entry)iterator2.next();
            if(isOut(node.getValue())) {
                System.out.println(node.getKey() + "==" + node.getValue());
            }
            
        }
        iterator2 = entrySet.iterator();
    }
    
    public static boolean isOut(Object object) {
        if(!(object instanceof Employee)) {
            return false;
        }
        Employee e = (Employee)object;
        return e.getSalary() > 18000;
    }
​
}
​
class Employee{
    private String name;
    private int id;
    private double salary;
    
    public Employee(String name, int id, double salary) {
        super();
        this.name = name;
        this.id = id;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    
    
    
    @Override
    public String toString() {
        return "Employee [name=" + name + ", id=" + id + ", salary=" + salary + "]";
    }
}

程式輸出:

1001--Employee [name=小范, id=1001, salary=22000.0]

1003--Employee [name=小雨, id=1003, salary=23000.0]

=============================================

1001--Employee [name=小范, id=1001, salary=22000.0]

1003--Employee [name=小雨, id=1003, salary=23000.0]