1. Student management system (completed after class)
1.1 modification
//modify private static void updateStudent(ArrayList<Student> list) { //Create keyboard entry object Scanner sc = new Scanner(System.in); System.out.println("Please enter the number of the student you want to modify:"); //Get the entered student number int input_id = sc.nextInt(); //Traversal list set for (int i = 0; i < list.size(); i++) { //Take out each student Student s = list.get(i); //Get student number int list_id = s.getId(); //Judge whether the number entered is equal to the student number taken from the set if(input_id == list_id){ //Description found //Enter new information and modify System.out.println("Please enter the new student name:(Keep the original value, please enter 0)"); String name = sc.next(); System.out.println("Please enter the new student gender:(Keep the original value, please enter 0)"); String sex = sc.next(); System.out.println("Please enter the new student's birthday:(Keep the original value, please enter 0)"); String birthday = sc.next(); //If the above input 0 in the console belongs to the string "0" //Judge whether to modify the name if(!"0".equals(name)){ //Indicate that you want to modify s.setName(name); } //Judge whether to modify gender if(!"0".equals(sex)){ //Indicate that you want to modify s.setSex(sex); } //Determine whether to modify the birthday if(!"0".equals(birthday)){ //Indicate that you want to modify //Modify birthday s.setBirthday(birthday); //Pass the new birthday into the tool class to calculate the new age int age = Utils.birthdayToAge(birthday);//New age s.setAge(age); } System.out.println("[Modified successfully]"); //Stop method updatestent return; } } //If it can be executed here, it means that the if statement in the for loop above is not executed, because if the statement is executed, there is a return direct end method //In other words, no student ID equal to the entered student ID was found System.out.println("[The number you entered does not exist]"); }
1.2 deletion
//Delete student private static void deleteStudent(ArrayList<Student> list) { //Creating objects for keyboard entry Scanner sc = new Scanner(System.in); System.out.println("Please enter the number of the student you want to delete:"); //Entered student number int input_id = sc.nextInt(); /* The concurrent modification exception will not be reported here, because it will only be reported when Iterator or enhanced for loop is used The concurrent modification exception is located in the inner class Itr class It has nothing to do with iterators, so no concurrent modification exception will be reported */ //Ergodic set for (int i = 0; i < list.size(); i++) { //Take out the student object Student s = list.get(i); //Get the student number in the collection int list_id = s.getId(); //Judge whether the student number entered by the keyboard is consistent with the student number in the set if(input_id == list_id){ //Note student found, delete directly from collection list.remove(i);//Delete by index System.out.println("[Delete successfully]"); //End method return; } } //If it can be carried out here, no student can be found System.out.println("[You have entered the wrong number]"); }
2. Introduction to map set (mastery)
1. Map < K, V > belong to the two column set, one pair of data can be added at a time, and the two data have a mapping relationship.
For example: person and ID card, ID card and driver's license, husband and wife, etc. Both can be stored using a two column set Map.
2. The first generics of a two column set Map: K is the key's shorthand representation, V is the value's shorthand representation, and the whole is called the key value pair
3. Difference between single column set and double column set
3.Map inheritance system (understanding)
- HashMap < K, V >: the hash table structure used to store data. The access order of elements cannot be consistent. To ensure the uniqueness and non repetition of the key, the hashCode() method and the equals() method of the key need to be rewritten. Hash table control key, unique key.
- LinkedHashMap < K, V >: there is a subclass LinkedHashMap under the HashMap, and the hash table structure + linked table structure is used to store data. The access order of elements can be ensured to be consistent through the chain list structure; the key can be guaranteed to be unique and not repeated through the hash table structure, and the hashCode() method and equals() method of the key need to be rewritten.
- TreeMap < K, V >: TreeMap set has no special function compared with Map. The underlying data structure is a red black tree. You can sort the * * keys of elements in two ways: natural sorting and comparator sorting
- Hashtable is replaced by HashMap collection, but it is less efficient than HashMap
- ConcurrentHashMap is multithreaded safe, and its efficiency is lower than that of Hashtable
tips: the collection in the Map interface has two generic variables < K, V >. When using, two generic variables should be given data types. The data types of the two generic variables < K, V > can be the same or different.
4. Introduction to map interface method (mastery)
package com.itheima.sh.map_method_01; import java.util.HashMap; import java.util.Map; import java.util.Set; /* Map There are many methods defined in the interface, the common ones are as follows: 1.public V put(K key, V value)`: Adds the specified key and the specified value to the Map collection. explain: 1)If the newly added key does not exist when put is executed to add data, add it directly and return null 2)When performing put to add data, if the newly added key exists, the newly added value will overwrite the previous value and return the old value 2.public V remove(Object key)`: Delete the key value pair element corresponding to the specified key in the Map collection, and return the value of the deleted element. 3.public V get(Object key)` Gets the corresponding value in the Map collection according to the specified key. 4.public Set<K> keySet()`: Get all the keys in the Map collection and store them in the Set collection. 5.public Set<Map.Entry<K,V>> entrySet()`: Gets the Set of all key value pairs in the Map Set. Note: this method means to obtain all key value pairs in the map Set, store them in the single column Set, and the key value pairs belong to the Map.Entry < K, V > type 6.public boolean containKey(Object key)`:Determines whether the key exists in the collection. Return true if included, false otherwise 7. int size() Returns the number of key value mapping relationships in this mapping. Set length */ public class MapDemo01 { public static void main(String[] args) { method_2(); } private static void method_2() { Map<String, String> map = new HashMap<>(); //Add data map.put("Huang Xiaoming", "baby"); map.put("Nicholas Tse", "Faye Wong"); map.put("Wang Feng", "Zhang Ziyi"); map.put("Deng Chao", "Sun Li"); map.put("Liuyan", "baby"); // 2.public V remove(Object key) ` delete the key value pair element corresponding to the specified key in the Map collection, and return the value of the deleted element. // String value = map.remove("Liuyan"); // System.out.println("value = " + value); // System.out.println ("map =" + map); / / map = {Deng Chao = Sun Li, Xie Tingfeng = Wang Fei, Wang Feng = Zhang Ziyi, Huang Xiaoming = baby} // // // //3.public V get(Object key) ` get the corresponding value in the Map collection according to the specified key. // //Demand: get value according to Nicholas Tse // String value2 = map.get (Nicholas Tse); // System.out.println ("Value2 =" + Value2); / / Faye Wang //4. Public Set < k > keyset() `: get all the keys in the Map Set and store them in the Set set. Set<String> keys = map.keySet(); System.out.println("keys = " + keys); //5.public Set< Map.Entry < K, V > > entryset() `: get the set of all key value pairs in the map set. Set<Map.Entry<String, String>> entries = map.entrySet(); //entries = [Deng Chao = Sun Li, Xie Tingfeng = Wang Fei, Liu Yan = baby, Wang Feng = Zhang Ziyi, Huang Xiaoming = baby] System.out.println("entries = " + entries); //6. Public Boolean containerkey (object key) ` determines whether the key exists in the collection. Return true if included, false otherwise //Whether the demand judgment includes Wang Feng boolean boo = map.containsKey("Wang Feng"); System.out.println("boo = " + boo);//boo = true //7. int size() returns the number of key value mapping relationships in this mapping. Set length System.out.println(map.size()); // Void putall (map <? Extends K,? Extends V > m) puts the map set of the parameter into the map set of the call //Create an empty map collection Map<String, String> map2 = new HashMap<>(); //Put the data of map collection into map2 map2.putAll(map); //map2 = {Deng Chao = Sun Li, Liu Yan = baby, Wang Feng = Zhang Ziyi, Xie Tingfeng = Wang Fei, Huang Xiaoming = baby} System.out.println("map2 = " + map2); } private static void method_1() { //Creating objects with Subclasses //HashMap() constructs an empty HashMap with a default initial capacity (16) and a default load factor (0.75). Map<String, String> map = new HashMap<>();//Generic types of keys and values can be inconsistent //Add data //1) If the newly added key does not exist when put is executed to add data, add it directly and return null String s = map.put("Huang Xiaoming", "baby"); System.out.println("s = " + s);//s = null System.out.println(map);//Huang Xiaoming = baby} //For the key Huang Xiaoming already exists, the put method is to overwrite the old value baby before the new value Yang power and return the old value baby to s1 //2) When performing put to add data, if the newly added key exists, the newly added value will overwrite the previous value and return the old value String s1 = map.put("Huang Xiaoming", "Yang Mi"); System.out.println("s1 = " + s1);//s1 = baby System.out.println(map);//{Huang Xiaoming = Yang Mi} } }
Summary:
1.public V put(K key, V value) ` adds the specified key and the specified value to the Map collection. explain: 1) If the newly added key does not exist when put is executed to add data, add it directly and return null 2) When performing put to add data, if the newly added key exists, the newly added value will overwrite the previous value and return the old value 2.public V remove(Object key) ` delete the key value pair element corresponding to the specified key in the Map collection, and return the value of the deleted element. 3.public V get(Object key) ` get the corresponding value in the Map collection according to the specified key. 4. Public Set < k > keyset() `: get all the keys in the Map Set and store them in the Set set. 5.public Set< Map.Entry < K, V > > entryset() `: get the set of all key value pairs in the map set. Note: this method means to obtain all key value pairs in the map Set, store them in the single column Set, and the key value pairs belong to the Map.Entry < K, V > type 6. Public Boolean containerkey (object key) ` determines whether the key exists in the collection. Return true if included, false otherwise 7. int size() returns the number of key value mapping relationships in this mapping. Set length
5.Map traversal
1. Use the keySet method to traverse (understand)
- The method to be used for this method:
public V get(Object key) ` gets the corresponding value in the Map collection according to the specified key. Public Set < k > keyset() `: get all the keys in the Map Set and store them in the Set set.
- graphic
- code implementation
package com.itheima.sh.map_iterator_02; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /* Traversal with keySet method */ public class KeySetDemo01 { public static void main(String[] args) { //1. create collection object Map<String, String> map = new HashMap<>(); //2. Add data map.put("Huang Xiaoming", "baby"); map.put("Deng Chao", "Sun Li"); map.put("Wang Feng", "Zhang Ziyi"); map.put("baby", "Rongrong"); //3. Use the set object to call the keySet method to get all the keys, that is, husband Set<String> keys = map.keySet(); //4. Traverse the Set set to get each key for(Iterator<String> it = keys.iterator();it.hasNext();){ //get data String key = it.next(); //Use the Map set object to call the get method to get the value wife according to the key String value = map.get(key); System.out.println(key+"--"+value); } } }
Summary:
1. The keySet method is used to iterate the set twice. The first is put into the Iterator iterator, and the second is to use the get method.
[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-kWZbdb4C-1592807422288)(/image-20200518111653376.png))
2. Use entrySet to traverse Map set (Master)
-
usage method:
-
Methods in the Map interface:
public Set< Map.Entry < K, V > > entryset() `: get the set of all key value pairs in the map set. Note: this method means to obtain all key value pairs in the map Set, store them in the single column Set, and the key value pairs belong to the Map.Entry <K,V>
-
use Map.Entry Methods in the interface:
K getKey() returns the key corresponding to this item. V getValue() returns the value corresponding to this item.
-
-
graphic
[failed to transfer the pictures in the external chain. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-bPIMRpdC-1592807422289)(/image-20200518112903000.png))
-
Code demonstration
package com.itheima.sh.map_iterator_02; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /* Traversal using the entrySet method */ public class EntrySetDemo02 { public static void main(String[] args) { //1. Create a collection object Map<String, String> map = new HashMap<>(); //2. Add data map.put("Huang Xiaoming", "baby"); map.put("Deng Chao", "Sun Li"); map.put("Wang Feng", "Zhang Ziyi"); map.put("baby", "Rongrong"); //3. Get the key value and put the whole object into the Set set Set<Map.Entry<String, String>> entries = map.entrySet(); //4. Traverse the single column Set to get each key value pair object, which is the marriage certificate for(Iterator<Map.Entry<String, String>> it = entries.iterator();it.hasNext();){ //5. Take out the key value to the whole Map.Entry<String, String> entry = it.next(); //6. Use the entry object call method to get the key and value String key = entry.getKey(); String value = entry.getValue(); //7. Output System.out.println(key+"---"+value); } } }
Summary:
1. It will be used in the future, because of its high efficiency, it only iterates once
2. Get the key value of the whole Map.Entry Type, then use Map.Entry The methods in get the key and value respectively:
K getKey() returns the key corresponding to this item. V getValue() returns the value corresponding to this item.
6. Common subclasses of map
1.HashMap class (must master)
1. The bottom layer of the HashMap class is a hash table data structure and control key
2. The class of the object in the HashMap key position must override the hashCode and equals methods
3. The HashMap set starts from jdk1.2:
1) Thread unsafe 2) High efficiency 3) Key and value can be null 4) Access disorder
Code demonstration:
package com.itheima.sh.hashmap_03; import java.util.HashMap; /* Note: if the underlying hash table controls the key, the class of the object at the key position must override the hashCode and equals methods */ public class HashMapDemo01 { public static void main(String[] args) { //1. Create a collection object HashMap() to construct an empty HashMap with default initial capacity (16) and default load factor (0.75). HashMap<Student, String> hm = new HashMap<Student, String>(); //2. Add data to the collection hm.put(new Student("Zhang San", 18), "Shanghai"); hm.put(new Student("Li Si", 20), "Beijing"); hm.put(new Student("Wang Wu", 19), null); hm.put(null, null); hm.put(null, null); hm.put(null, null); hm.put(null, null); hm.put(null, null); hm.put(null, null); //Modification function hm.put(new Student("Zhang San", 18), "Heilongjiang"); //hm = {Student{name = 'Wang Wu', age=19}=null, null=null, Student{name = 'Zhang San', age=18} = Heilongjiang, Student{name = 'Li Si', age=20} = Beijing} System.out.println("hm = " + hm); } }
Summary:
1.HashMap is only available after jdk1.2. It replaces Hashtable to improve efficiency
2. The underlying hash table data structure controls the key, so the class of the object where the key is located must override the hashCode and equals methods
3. Both the key and value of the HashMap collection can be null, but the key location can only be a null
2.Hashtable class (learn)
1. Data is available in jdk1.0
2. Safe but inefficient
3. The bottom layer is hash table data structure and control key
4. The key and value of the collection cannot be null
5. It has been replaced by HashMap since 1.2, which is more efficient
Code demonstration:
package com.itheima.sh.hashtable_04; import java.util.Hashtable; /* Hashtable Class (understanding) 1.Data is available in jdk1.0 2.Safe, but inefficient 3.The bottom layer is hash table data structure, control key 4.The key and value of the collection are not allowed to be null 5.It has been replaced by HashMap since 1.2, which is more efficient */ public class HashtableDemo01 { public static void main(String[] args) { //Create the collection object Hashtable() to construct a new empty hash table with the default initial capacity (11) and load factor (0.75). Hashtable<String, Integer> ht = new Hashtable<>(); //Add data ht.put("Lau Andy", 50); ht.put("Jacky Cheung", 55); ht.put("Guo Fucheng", 52); ht.put("dawn", 51); ht.put("Lau Andy", 48); //Exception in thread "main" java.lang.NullPointerException Null pointer exception reported /* Hashtable The key and value of cannot be null because: public synchronized V put(K key, V value) { // Make sure the value is not null if (value == null) { throw new NullPointerException(); } key If it's null, it's equivalent to null.hashCode() null pointer int hash = key.hashCode(); } */ ht.put(null, 20); System.out.println("ht = " + ht); } }
3. LinkedHashMap (understanding)
package com.itheima.sh.linkedhashmap_05; import java.util.LinkedHashMap; /* LinkedHashMap 1.There are two data structures in the bottom layer: 1)Hash table: store data to ensure unique data 2)Double linked list: ensure orderly access */ public class LinkedHashMapDemo01 { public static void main(String[] args) { //LinkedHashMap() constructs an empty insert order LinkedHashMap instance with default initial capacity (16) and load factor (0.75). LinkedHashMap<String, Integer> ht = new LinkedHashMap<>(); ht.put("Lau Andy", 50); ht.put("Jacky Cheung", 55); ht.put("Guo Fucheng", 52); ht.put("dawn", 51); ht.put("Lau Andy", 48); //ht = {Liu Dehua = 48, Zhang Xueyou = 55, Guo Fucheng = 52, liming = 51} System.out.println("ht = " + ht); } }
Summary:
LinkedHashMap
1. There are two data structures in the bottom layer:
1) Hash table: store data to ensure unique data
2) Double linked list: ensure orderly access
4.TreeMap class (learn)
1. The bottom layer is a red black tree data structure, which controls keys and can sort them. How to sort is the construction method used:
1) TreeMap() is in ascending order of size for keys, and non custom classes (String Integer) are sorted in ascending order of size 2) Treemap (comparator <? Super k > comparator) sorts according to the specified rules according to the key, Parameter: comparator belongs to the type of comparator of user-defined comparator interface. The specific sorting rules are specified by the sorting method that implements the interface: int compare(T o1, T o2) o1 - o2 ascending O 2 - O 1 descending order
Code demonstration:
package com.itheima.sh.treemap_06; import java.util.Comparator; import java.util.TreeMap; /* 1) TreeMap() The key is in ascending order of size, and the non custom class (String Integer) is in ascending order of size. It cannot be a custom class, otherwise ClassCastException will be reported 2)TreeMap(Comparator<? super K> comparator) Sort by key according to specified rules, Parameter: comparator belongs to the type of comparator of user-defined comparator interface. The specific sorting rules are specified by the sorting method that implements the interface: int compare(T o1, T o2) o1 - o2 Ascending order o2 - o1 Descending order */ public class TreeMapDemo01 { public static void main(String[] args) { method_3(); } //Demand: from small to large platoon according to age private static void method_3() { //Create collection object TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.age - o2.age; } }); //Add data tm.put(new Student("Zhang San", 20), "Shanghai"); tm.put(new Student("Li Si", 17), "Hangzhou"); tm.put(new Student("Wang Wu", 19), "Beijing"); tm.put(new Student("Zhang San", 20), "Shanghai"); System.out.println(tm); } //1. Requirements: sorted by integer from large to small /* 2)TreeMap(Comparator<? super K> comparator) Sort by key according to specified rules, Parameter: comparator belongs to the type of comparator of user-defined comparator interface. The specific sorting rules are specified by the sorting method that implements the interface: int compare(T o1, T o2) o1 - o2 Ascending order o2 - o1 Descending order */ private static void method_2() { //1. create collection object TreeMap<Integer, String> tm = new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); //Add data tm.put(50, "Lau Andy"); tm.put(56, "Jacky Cheung"); tm.put(48, "Guo Fucheng"); tm.put(53, "dawn"); //tm = {56 = Zhang Xueyou, 53 = liming, 50 = Liu Dehua, 48 = Guo Fucheng} System.out.println("tm = " + tm); } //1) TreeMap() is in ascending order of size for keys, and non custom classes (String Integer) are sorted in ascending order of size private static void method_1() { //1. create collection object TreeMap<String, String> tm = new TreeMap<>(); //2. Add data tm.put("abcdef", "Lau Andy"); tm.put("ADDF", "Jacky Cheung"); tm.put("abc", "Guo Fucheng"); tm.put("zhag", "dawn"); //Output tm = {ADDF = Zhang Xueyou, abc = Guo Fucheng, abcdef = Liu Dehua, zhag = Liming} System.out.println("tm = " + tm); } }
Summary:
- TreeMap() is in ascending order of size for keys, and non custom classes (String Integer) are sorted in ascending order of size. They cannot be custom classes, otherwise ClassCastException will be reported
2) Treemap (comparator <? Super k > comparator) sorts according to the specified rules according to the key,
Parameter: comparator belongs to the type of comparator of user-defined comparator interface. The specific sorting rules are specified by the sorting method that implements the interface:
int compare(T o1, T o2)
o1 - o2 ascending
o2 - o1 in descending order
7.Map set exercise (must be completed after class)
**Requirement: * * count the number of occurrences of each character in a string.
Code demonstration:
package com.itheima.sh.map_test_07; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; /* Requirement: count the number of occurrences of each character in a string. analysis: "akajahKLAK19" Number of characters a 3 k 1 j 1 h 1 K 1 ................... 1.map The set stores the character and the number of times 1 to the map set directly without the character 2.If there are characters in the map set, put(a,3) in the map set according to the number of character acquisition times and then add 1 Step: 1.Creating objects for keyboard entry 2.Get the entered string 3.Create a Map set object with characters as key times as value 4.Traversing the entered string to extract each character 5.Determine whether the key position of the Map set contains this character Does not contain: the description is the first operation of the character, storing the character and the number of times 1 in the set Include: the description is not the first time to operate the character. Use the character as the key and the value get(key) method to get the number of times, and then the number of times + 1. Finally, store the character and the number of times after adding 1 to the map in 6.Traversal map set output characters and times */ public class Test01 { public static void main(String[] args) { //1. Create the object of keyboard entry Scanner sc = new Scanner(System.in); //2. Get the entered string System.out.println("Please enter a string:"); String inputStr = sc.next(); //3. Create a Map set object, and the number of characters as key times as value HashMap<Character, Integer> map = new HashMap<>(); //4. Traverse the input string to get each character inputStr.length().fori for (int i = 0; i < inputStr.length(); i++) {//i for index //Get character char key = inputStr.charAt(i); // 5. Judge whether the key position of the Map set contains this character if(map.containsKey(key)){ //Include: the description is not the first time to operate the character. Use the character as the key in combination with the value get(key) method // Get the number of times in the map, then the number of times + 1, and finally store the characters and the number of times after adding 1 to the //Get times is value Integer countValue = map.get(key); //Then times + 1 countValue++; //Finally, the character and the number of times after adding 1 are stored in the map.put(key, countValue); }else{ // Does not contain: the description is the first operation of the character, storing the character and the number of times 1 in the set map.put(key, 1); } } //6. Output characters and times of traversing map set //Get key value pair object Set<Map.Entry<Character, Integer>> entries = map.entrySet(); //Traversal set set for (Map.Entry<Character, Integer> entry : entries) { //entry represents key value pair object //Get key Character key = entry.getKey(); Integer value = entry.getValue(); // \t means tab System.out.println("character:\t"+key+"\t frequency:\t"+value); } } }
8. Nesting of sets
First, a collection can only store reference data types, and the collection itself is a reference data type, so the collection can continue to store the collection. Various collections can be nested in java.
1.List nested list
package com.itheima.sh.collection_map_contains_08; import java.util.ArrayList; import java.util.Collections; /* Requirement: if there are two class names, they are stored in two sets respectively, and finally in one set. give an example: Buy mobile phones on Taobao: Home phone: first install the inside and then the outside (add from inside to outside) Buyer's mobile phone: first remove the outside, and finally get the inside (from the outside to the inside) Nested set usage: Add data: (add from inside out) Get data: (from outside to inside) */ public class ListDemo01 { public static void main(String[] args) { //Create a collection of classes ArrayList<String> list1 = new ArrayList<>(); //Add data Collections.addAll(list1, "Zhang San", "Liuyan"); ArrayList<String> list2 = new ArrayList<>(); //Add data // Collections.addAll(list2, "Li Si", "Yang Mi"); //Create collection store list1 list2 //List set list ArrayList<ArrayList<String>> allList = new ArrayList<>(); //Store list1 list2 in allList //Add data: (add from inside out) Collections.addAll(allList, list1, list2); //Traverse to get data: (from outside to inside) //First get the outer set: allList gets the inner set list1 list2 //Get the outermost collection first: allList for (ArrayList<String> outList : allList) { //Take out the data in each collection. The first outList represents list1 and the second outList represents list2 for (String s : outList) { System.out.println(s); } } } }
Summary:
1. Use rules of nested sets:
Add data: (add from inside out)
Get data: (from outside to inside)
2.List nested Map
package com.itheima.sh.collection_map_contains_08; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; /* List Nested Map collection Requirements: there are two classes of students, which are stored in two maps, and then the maps of the two classes are stored in an ArrayList. */ public class ListMapDemo02 { public static void main(String[] args) { //1. Create Map collection object HashMap<String, String> map1 = new HashMap<>(); map1.put("hiema001", "Liuyan"); map1.put("hiema002", "Yang Mi"); HashMap<String, String> map2 = new HashMap<>(); map2.put("itcast001", "Guo Degang"); map2.put("itcast002", "Yue Yunpeng"); //2. Create ArrayList collection object ArrayList<HashMap<String, String>> list = new ArrayList<>(); list.add(map1); list.add(map2); //3. Traverse collection add: add from inside out get: get from outside in //3.1 traverse list set for (HashMap<String, String> m : list) { //3.2 traversal map set //3.2.1 obtaining key value pairs Set<Map.Entry<String, String>> entries = m.entrySet(); //3.2.2 get each key value pair for (Map.Entry<String, String> entry : entries) { //3.2.3 get key and value String key = entry.getKey(); String value = entry.getValue(); //3.2.4 output System.out.println(key+"----"+value); } } } }
Summary: add: add from inside out get: get from outside in
3.Map nested map
package com.itheima.sh.collection_map_contains_08; import java.util.HashMap; import java.util.Map; import java.util.Set; /* Map Set nested Map Requirement: there are two classes with class numbers of "black horse 188" and "black horse 189". The names of the students in the two classes are stored in two maps respectively */ public class MapMapDemo03 { public static void main(String[] args) { //1. Create Map set object to save student number and name HashMap<String, String> map1 = new HashMap<>(); map1.put("hiema001", "Liuyan"); map1.put("hiema002", "Yang Mi"); HashMap<String, String> map2 = new HashMap<>(); map2.put("itcast001", "Guo Degang"); map2.put("itcast002", "Yue Yunpeng"); //2. Create Map set to save class and student number name HashMap<String, HashMap<String, String>> allMap = new HashMap<>(); allMap.put("Black horse 188", map1); allMap.put("Black horse 189", map2); //3. Traverse map: get from the outside in //3.1 get the key value pair object of the outermost set Set<Map.Entry<String, HashMap<String, String>>> outEntries = allMap.entrySet(); //3.2 take out each key value pair in the outermost set for (Map.Entry<String, HashMap<String, String>> outEntry : outEntries) { //3.3 traverse the key and value of the outer set represented by the outEntry String outKey = outEntry.getKey(); System.out.println("The class is:"+outKey); //outValue means map1 map2 HashMap<String, String> outValue = outEntry.getValue(); //3.4 traversing the map set represented by outValue Set<Map.Entry<String, String>> InEntries = outValue.entrySet(); for (Map.Entry<String, String> inEntry : InEntries) { //Get the key and value of the inEntry set String key = inEntry.getKey(); String value = inEntry.getValue(); System.out.println(key+"---"+value); } } } }
Summary: add: add from inside out get: get from outside in
9. Use the set to simulate the game of fighting the landlord (it must be completed after class)
- graphic
-
code implementation
package com.itheima.sh.playcard_09; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; /* Fight the landlord game: Step: 1.Prepare cards 2.shuffle the cards 3.Licensing 4.Watch the cards Small A kind of */ public class PlayCard { public static void main(String[] args) { //1. Preparation card //1.1 create map set to save serial number and playing card HashMap<Integer, String> mapPoker = new HashMap<>(); //1.2 create set save sequence number ArrayList<Integer> numbersList = new ArrayList<>(); //1.3 create a collection store Decor ArrayList<String> colors = new ArrayList<>(); Collections.addAll(colors, "♣", "♦", "♠", "♥"); //1.4 create a set to store playing card numbers ArrayList<String> numbers = new ArrayList<>(); Collections.addAll(numbers, "2", "A", "K", "Q", "J"); for (int i = 10; i >= 3; i--) { numbers.add(i+""); } //Define variable as mapPoker sequence number int index = 0; //First add the king of size to the playing card mapPoker.put(index, "large☺"); //No. + 1 per time index++; mapPoker.put(index, "Small☺"); //No. + 1 per time index++; //numbers = [2, A, K, Q, J, 10, 9, 8, 7, 6, 5, 4, 3] // System.out.println("numbers = " + numbers); //1.5 combine the number of decors and playing cards A kind of Two Accession Two A kind of Two 80 Two A kind of A Accession A A kind of A 80 A //Numbers as outer cycles for (String thisNumber : numbers) { //Color as inner loop for (String thisColor : colors) { //Splicing String thisCard = thisColor + thisNumber; //Put playing cards in the map set mapPoker.put(index,thisCard);//♣2 //No. + 1 per time index++; } } // System.out.println(mapPoker); //1.6 add serial number for (int i = 0; i <= 53; i++) { numbersList.add(i); } // System.out.println(numbersList); // 2. Shuffle No Collections.shuffle(numbersList); //3. The license is issued with serial number //3.1 create three player sets ArrayList<Integer> fage = new ArrayList<>(); ArrayList<Integer> suoge = new ArrayList<>(); ArrayList<Integer> yanyan = new ArrayList<>(); ArrayList<Integer> dipai = new ArrayList<>(); //3.2 traverse the number set numbersList to retrieve each number for (int i = 0; i < numbersList.size(); i++) {//i for index //3.3 take out each serial number Integer thisNumber = numbersList.get(i);// numbersList.get(i) Indicates to get the sequence number in numberslist according to index I /* 3.4 The last three cards are reserved as base cards and the rest are given to three players respectively */ //Judge whether it is the last three cards if(i>=numbersList.size() - 3){//51 52 53 //It means that the last three cards are put into the base card collection dipai.add(thisNumber); }else{ //That's not the last three cards /* 3.5 Give the rest of the cards to the players Fage touch one Brother Suo touches the second picture Third sheet of petrography */ if(i % 3 == 0){ //Chow fage.add(thisNumber); }else if(i % 3 == 1){ //Brother Suo suoge.add(thisNumber); }else if(i % 3 == 2){ //Rock yanyan.add(thisNumber); } } } //4. Sort players and base cards Collections.sort(fage); Collections.sort(suoge); Collections.sort(yanyan); Collections.sort(dipai); //5. Watch the cards lookCard(mapPoker,fage,"Chow "); lookCard(mapPoker,suoge,"Brother Suo"); lookCard(mapPoker,yanyan,"Rock"); lookCard(mapPoker,dipai,"a hand"); } /* mapPoker:Stored serial number and playing cards 0 king 1 Xiao Wang list:It's player number 10 20 25 name:Received name */ private static void lookCard(HashMap<Integer, String> mapPoker, ArrayList<Integer> list, String name) { //Create StirngBuilder object StringBuilder sb = new StringBuilder(name).append(":"); //Traverse the list set to retrieve each sequence number for (Integer key : list) { //Get value according to key, i.e. playing card String value = mapPoker.get(key); //Put the value card in the buffer sb.append(value).append("\t"); } System.out.println(sb); } }