
Java基礎之:集合——Map
-
Map與Collection并列存在,用于保存具有映射關系的資料鍵值對:Key—Value
-
在Map中Key與Value都可以存放任何型別的資料,
-
Key是用Set來存放的,不允許重復,允許有null但只能有一個,常用String類作為Map的“鍵”(key)
-
Value是用Collection存放的,可以是Set也可以是List,所以當Value使用List時允許重復,且可以有多個null值,
-
key與value之間存在單向一對一關系,即通過指定key總能找到唯一的確定的一個value,
-
因為key是用Set存放的,而value是通過key進行查找回傳的,所以Map是無序的,
底層結構圖:

虛線為實作關系,實線為繼承關系,

Map介面常用方法
-
put:添加
-
get:根據鍵獲取值
-
size:獲取元素個數
-
isEmpty:判斷個數是否為0
-
containsKey:查找鍵是否存在
-
remove:根據鍵洗掉映射關系
-
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介面的遍歷方式
需要使用的方法:
-
containsKey():查找鍵是否存在
-
keySet():獲取所有的鍵,回傳一個Set集合
-
entrySet():獲取所有關系,回傳一個Set集合
-
values():獲取所有的值,回傳一個Collection集合
兩種遍歷方式(每種方式又分別有迭代器和增強for兩種):
-
遍歷鍵再通過鍵取出對應的值
-
直接遍歷整個鍵值對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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/240775.html
標籤:其他
上一篇:學習一下 SpringCloud (二)-- 服務注冊中心 Eureka、Zookeeper、Consul、Nacos
下一篇:Spring-前言序
