【Java】【基礎篇】day16:集合(HashMap、TreeMap)

前言

本期任務:畢向東老師Java視頻教程學習筆記(共計25天)


代碼

/*
Map集合:該集合存儲鍵值對。一對一對往裏存。而且要保證鍵的唯一性。
	1,添加。
		put(K key, V value)
		putAll(Map<? extends K,? extends V> m)

	2,刪除。
		clear()
		remove(Object key)

	3,判斷。
		containsValue(Object value)
		containsKey(Object key)
		isEmpty()


	4,獲取。
		get(Object key)
		size()
		values()

		entrySet()
		keySet()

Map
	|--Hashtable:底層是哈希表數據結構,不可以存入null鍵null值。該集合是線程同步的。jdk1.0.效率低。
	|--HashMap:底層是哈希表數據結構,允許使用 null 值和 null 鍵,該集合是不同步的。將hashtable替代,jdk1.2.效率高。
	|--TreeMap:底層是二叉樹數據結構。線程不同步。可以用於給map集合中的鍵進行排序。


和Set很像。
其實大家,Set底層就是使用了Map集合。


*/

import java.util.*;

public class MapDemo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        // 添加元素,如果是添加已存在的鍵,那麼後添加的值會覆蓋原有的鍵值對應值
        //使用put方法會返回被覆蓋的值,如果是無被覆蓋的值,則返回null
        System.out.println("put: "+map.put("01", "張三"));
        System.out.println("put: "+map.put("01", "張三1"));

        map.put("02", "李四");
        map.put("03", "王五");

        System.out.println("remove: "+ map.remove("01"));

        // 可以通過get方法的返回制來判斷一個鍵是否存在,不存在則返回null
        System.out.println("get: "+ map.get("02"));
        System.out.println("get: "+ map.get("05"));

        System.out.println("ContainsKey: "+map.containsKey("01"));
        System.out.println("ContainsKey: "+map.containsKey("05"));

        // 獲取map集合中所有的值
        Collection<String> coll = map.values();
        System.out.println(coll);
        System.out.println(map);






    }
}

/*
map集合的兩種取出方式:
1,Set<k> keySet:將map中所有的鍵存入到Set集合。因爲set具備迭代器。
	所有可以迭代方式取出所有的鍵,在根據get方法。獲取每一個鍵對應的值。


	Map集合的取出原理:將map集合轉成set集合。在通過迭代器取出。


2,Set<Map.Entry<k,v>> entrySet:將map集合中的映射關係存入到了set集合中,
				而這個關係的數據類型就是:Map.Entry
*/

import java.util.*;

public class MapDemo2 {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("張三", "01");
        map.put("張三", "02");
        map.put("李四", "01");
        map.put("王五", "03");

        // Map遍歷方式一

//        //  先獲取map集合的所有鍵的Set集合,keySet();
//        Set<String> keySet = map.keySet();
//
//        // 有了Set集合,就可以獲取其迭代器
//        Iterator<String> it = keySet.iterator();
//
//        while (it.hasNext()) {
//            String key = it.next();
//            System.out.println("key: " + key + " value: " + map.get(key));
//        }

        // Map遍歷方式二

        // 將Map集合中的映射關係取出,存入到Set集合中
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        Iterator<Map.Entry<String, String>> it = entrySet.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> me = it.next();
            System.out.println("key: " + me.getKey() + " value: " + me.getValue());
        }

    }

}


/*
				Entry其實就是Map中的一個static內部接口。
				爲什麼要定義在內部呢?
				因爲只有有了Map集合,有了鍵值對,纔會有鍵值的映射關係。
				關係屬於Map集合中的一個內部事物。
				而且該事物在直接訪問Map集合中的元素。
*/


/*
interface Map {
    public static interface Entry {
        public abstract Object getKey();

        public abstract Object getValue;
    }
}

class HashMap implements Map {
    class HashMap implements Map.Entry {
        public Object getKey() {
        }

        public Object getValue() {
        }
    }
}

*/
/*
map擴展知識。

map集合被使用是因爲具備映射關係。

"yureban"   Student("01" "zhangsan");

"yureban" Student("02" "lisi");

"jiuyeban" "01" "wangwu";
"jiuyeban" "02" "zhaoliu";

一個學校有多個教室。每一個教室都有名稱。


*/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

class Student{
    private String id;
    private String name;

    Student(String id, String name){
        this.id = id;
        this.name = name;
    }

    public String toString (){
        return id + "::"+name;
    }

}

public class MapDemo3 {
    public static void main(String[] args) {

        // 傳智播客(czbk)下面有兩個班:預熱班(yure)、就業班(jiuye)
        HashMap<String, List<Student>> czbk = new HashMap<String, List<Student>>();

        List<Student> yure = new ArrayList<Student>();
        List<Student> jiuye = new ArrayList<Student>();

        czbk.put("yure", yure);
        czbk.put("jiuye", jiuye);

        // 預熱班有兩個學生,張三和李四
        yure.add(new Student("01", "zhangsan"));
        yure.add(new Student("02", "lisi"));

        // 就業班有兩個學生,張三和王五
        jiuye.add(new Student("01", "zhangsan"));
        jiuye.add(new Student("03", "wangwu"));

        // 遍歷所有班級的所有學生信息
        Iterator<String> it = czbk.keySet().iterator();
        while (it.hasNext()){
            String roomName = it.next();
            List<Student> room = czbk.get(roomName);

            System.out.println(roomName);
            getInfos(room);
        }
    }
    public static void getInfos(List<Student> list){
        Iterator<Student> it = list.iterator();
        while (it.hasNext()){
            System.out.println(it.next().toString());
        }
    }
}
/*
每一個學生都有對應的歸屬地。
學生Student,地址String。
學生屬性:姓名,年齡。
注意:姓名和年齡相同的視爲同一個學生。
保證學生的唯一性。



1,描述學生。

2,定義map容器。將學生作爲鍵,地址作爲值。存入。

3,獲取map集合中的元素。

*/

import java.util.*;

/*
姓名和年齡相同的視爲同一個學生,保證學生的唯一性:
    - 實現Comparable接口,覆蓋compareTo函數
    - 覆蓋hashCode函數
    - 覆蓋equals函數
*/

class Student1 implements Comparable<Student1> {
    private int age;
    private String name;

    Student1(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String toString() {
        return name + "::" + age;
    }

    public int compareTo(Student1 s) {
        int num = ((Integer) age).compareTo((Integer) s.age);
        if (num == 0) {
            return name.compareTo(s.name);
        }
        return num;
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof Student1)) {
            throw new RuntimeException("類型不匹配");
        }

        Student1 s = (Student1) obj;
        return s.name == name && s.age == age;
    }

    public int hashCode() {
        return name.hashCode() + 47 * age;
    }
}


public class MapTest {
    public static void main(String[] args) {
        HashMap<Student1, String> map = new HashMap<Student1, String>();
        map.put(new Student1(10, "張三"), "北京");
        map.put(new Student1(11, "張三"), "上海");
        map.put(new Student1(10, "李四"), "福建");
        map.put(new Student1(12, "王五"), "成都");

        Set<Map.Entry<Student1, String>> entrySet = map.entrySet();
        Iterator<Map.Entry<Student1, String>> it = entrySet.iterator();

        while (it.hasNext()) {
            Map.Entry<Student1, String> me = it.next();
            System.out.println("key: " + me.getKey().toString() + ", " + "value: " + me.getValue());
        }


    }
}
import java.util.*;

/*
需求:對學生對象的年齡進行升序排序。

因爲數據是以鍵值對形式存在的。
所以要使用可以排序的Map集合。TreeMap。


思路一:直接在Student類中實現Comparable接口,使得學生類可比較
思路二:在外部新建一個比較器

*/

class Student2 implements Comparable<Student2> {
    private int age;
    private String name;

    Student2(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String toString() {
        return name + "::" + age;
    }

    public int compareTo(Student2 s) {
        int num = ((Integer) age).compareTo((Integer) s.age);
        if (num == 0) {
            return name.compareTo(s.name);
        }
        return num;
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof Student2)) {
            throw new RuntimeException("類型不匹配");
        }

        Student2 s = (Student2) obj;
        return s.name == name && s.age == age;
    }

    public int hashCode() {
        return name.hashCode() + 47 * age;
    }
}

class StuNameComparable implements Comparator<Student2> {
    public int compare(Student2 s1, Student2 s2) {
        int num = s1.getName().compareTo(s2.getName());
        if (num == 0) {
            return ((Integer) s1.getAge()).compareTo((Integer) s2.getAge());
        }
        return num;
    }
}


public class MapTest2 {
    public static void main(String[] args) {
        TreeMap<Student2, String> map = new TreeMap<Student2, String>(new StuNameComparable());
//        TreeMap<Student2, String> map = new TreeMap<Student2, String>();
        map.put(new Student2(10, "張三"), "北京");
        map.put(new Student2(11, "張三"), "上海");
        map.put(new Student2(10, "李四"), "福建");
        map.put(new Student2(12, "王五"), "成都");

        Set<Map.Entry<Student2, String>> entrySet = map.entrySet();
        Iterator<Map.Entry<Student2, String>> it = entrySet.iterator();

        while (it.hasNext()) {
            Map.Entry<Student2, String> me = it.next();
            System.out.println("key: " + me.getKey().toString() + ", " + "value: " + me.getValue());
        }


    }
}
import java.util.*;

/*
練習:
"sdfgzxcvasdfxcvdf"獲取該字符串中的字母出現的次數。

希望打印結果:a(1)c(2).....

通過結果發現,每一個字母都有對應的次數。
說明字母和次數之間都有映射關係。

注意了,當發現有映射關係時,可以選擇map集合。
因爲map集合中存放就是映射關係。


什麼使用map集合呢?
當數據之間存在這映射關係時,就要先想map集合。

思路:
1,將字符串轉換成字符數組。因爲要對每一個字母進行操作。

2,定義一個map集合,因爲打印結果的字母有順序,所以使用treemap集合。

3,遍歷字符數組。
	將每一個字母作爲鍵去查map集合。
	如果返回null,將該字母和1存入到map集合中。
	如果返回不是null,說明該字母在map集合已經存在並有對應次數。
	那麼就獲取該次數並進行自增。,然後將該字母和自增後的次數存入到map集合中。覆蓋調用原理鍵所對應的值。

4,將map集合中的數據變成指定的字符串形式返回。



*/
public class MapTest3 {
    public static void main(String[] args) {
        String str = "sdfgzxcvasdfxcvdf";
        System.out.println(charCount(str));
    }


    public static String charCount(String str) {
        /*
            1,將字符串轉換成字符數組。因爲要對每一個字母進行操作。

            2,定義一個map集合,因爲打印結果的字母有順序,所以使用treemap集合。

            3,遍歷字符數組。
                將每一個字母作爲鍵去查map集合。
                如果返回null,將該字母和1存入到map集合中。
                如果返回不是null,說明該字母在map集合已經存在並有對應次數。
                那麼就獲取該次數並進行自增。,然後將該字母和自增後的次數存入到map集合中。覆蓋調用原理鍵所對應的值。

            4,將map集合中的數據變成指定的字符串形式返回。
        */

        // 1,將字符串轉換成字符數組。因爲要對每一個字母進行操作。
        char[] arr = str.toCharArray();

        // 2,定義一個map集合,因爲打印結果的字母有順序,所以使用treemap集合。
        TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();

        // 3,遍歷字符數組。
        for (int x = 0; x < arr.length; x++) {
            if (!(arr[x] >= 'A' && arr[x] <= 'Z' || arr[x] >= 'a' && arr[x] <= 'z'))
                continue;

            if (tm.get(arr[x]) != null) {
                tm.put(arr[x], tm.get(arr[x]) + 1);
            } else {
                tm.put(arr[x], 1);
            }
        }

        // 4,將map集合中的數據變成指定的字符串形式返回。
        StringBuilder sb = new StringBuilder();

        Set<Map.Entry<Character, Integer>> entrySet = tm.entrySet();
        Iterator <Map.Entry<Character, Integer>> it = entrySet.iterator();
        while (it.hasNext()){
            Map.Entry<Character, Integer> me = it.next();
            sb.append(me.getKey()+"("+me.getValue()+")");
        }
        return sb.toString();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章