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

    技术2022-07-17  62

    前言

    本期任务:毕向东老师Java视频教程学习笔记(共计25天)

    原视频链接:黑马程序员_毕向东_Java基础视频教程day01:编写HelloWorld程序day02:操作符与条件选择语句day03:循环语句与函数day04:数组day07:继承、抽象类与接口day08:多态day09:异常处理day11:多线程day12:线程安全与同步机制day13:String类day14:集合(ArrayList,LinkedList,HashSet)day15:集合(TreeSet)和泛型)day16:集合(HashMap、TreeMap)day17:集合框架的工具类(Arrays、Collections)day18:IO流(字符流读写)day19:IO流(字节流、转换流读写)day20:IO流(File对象)

    代码

    /* 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(); } }
    Processed: 0.030, SQL: 9