1.Map collection
1.1 Map Set Overview and Characteristics [Understanding]
-
Overview of Map Collections
Interface Map < K, V > K: Type of Key; V: Type of Value
-
Characteristics of Map Sets
- Key-value pair mapping
- A key corresponds to a value
- Keys cannot be duplicated, values can be duplicated
- Element access disorder
-
Basic Use of Map Collections
public class MapDemo01 { public static void main(String[] args) { //Creating Collection Objects Map<String,String> map = new HashMap<String,String>(); //V put(K key, V value) associates the specified value with the specified key in the mapping map.put("itheima001","Lin Qingxia"); map.put("itheima002","Zhang Manyu"); map.put("itheima003","Wang Zuxian"); map.put("itheima003","Liu Yan"); //Output Set Object System.out.println(map); } }
Basic Functions of 1.2 Map Set [Application]
-
Method Introduction
Method name Explain V put(K key,V value) Adding elements V remove(Object key) Delete key-value pair elements by key void clear() Remove all key-value pair elements boolean containsKey(Object key) Determines whether the collection contains the specified key boolean containsValue(Object value) Determine whether a collection contains a specified value boolean isEmpty() Judging whether a set is empty int size() The length of the set, that is, the number of key-value pairs in the set -
Sample code
public class MapDemo02 { public static void main(String[] args) { //Creating Collection Objects Map<String,String> map = new HashMap<String,String>(); //V put(K key,V value): Add elements map.put("Zhang Wuji","Zhao Min"); map.put("Guo Jing","Huang Rong"); map.put("Yang Guo","Little dragon maiden"); //V remove(Object key): Delete key-value pair elements by key // System.out.println(map.remove("Guojing"); // System.out.println(map.remove("Guoxiang"); //void clear(): Remove all key-value pair elements // map.clear(); //boolean containsKey(Object key): Determines whether a collection contains the specified key // System.out.println(map.containsKey("Guojing"); // System.out.println(map.containsKey("Guoxiang"); //boolean isEmpty(): Determines whether the collection is empty // System.out.println(map.isEmpty()); //int size(): The length of the set, that is, the number of key-value pairs in the set System.out.println(map.size()); //Output Set Object System.out.println(map); } }
1.3 Map Collection Acquisition Function [Application]
-
Method Introduction
Method name Explain V get(Object key) Get values based on keys Set keySet() Get a collection of all keys Collection values() Get the set of all values Set<Map.Entry<K,V>> entrySet() Gets a collection of all key-value pairs of objects -
Sample code
public class MapDemo03 { public static void main(String[] args) { //Creating Collection Objects Map<String, String> map = new HashMap<String, String>(); //Adding elements map.put("Zhang Wuji", "Zhao Min"); map.put("Guo Jing", "Huang Rong"); map.put("Yang Guo", "Little dragon maiden"); //V get(Object key): Get values based on keys // System.out.println(map.get("Zhang Wuji"); // System.out.println(map.get("Zhang Sanfeng"); //Set < K > keySet (): Gets a collection of all keys // Set<String> keySet = map.keySet(); // for(String key : keySet) { // System.out.println(key); // } //Collection < V > values (): Gets a collection of all values Collection<String> values = map.values(); for(String value : values) { System.out.println(value); } } }
Traversal of 1.4 Map Sets (Mode 1) [Application]
-
Traversing train of thought
- The elements we just stored appear in pairs, so we think of Map as a collection of couples.
- Gather all the husbands together
- Travel through the collection of husbands and get every husband
- Find a wife according to her husband
- The elements we just stored appear in pairs, so we think of Map as a collection of couples.
-
Step analysis
- Gets a collection of all keys. Implement with keySet() method
- Traverse the collection of keys and get each key. Implementing with Enhanced for
- Find the value according to the key. Realization with get(Object key) method
-
code implementation
public class MapDemo01 { public static void main(String[] args) { //Creating Collection Objects Map<String, String> map = new HashMap<String, String>(); //Adding elements map.put("Zhang Wuji", "Zhao Min"); map.put("Guo Jing", "Huang Rong"); map.put("Yang Guo", "Little dragon maiden"); //Gets a collection of all keys. Implement with keySet() method Set<String> keySet = map.keySet(); //Traverse the collection of keys and get each key. Implementing with Enhanced for for (String key : keySet) { //Find the value according to the key. Realization with get(Object key) method String value = map.get(key); System.out.println(key + "," + value); } } }
Traversal of 1.5 Map Sets (Mode 2) [Application]
-
Traversing train of thought
- The elements we just stored appear in pairs, so we think of Map as a collection of couples.
- Collection of all marriage certificates
- Travel through the collection of marriage certificates and get each marriage certificate
- Obtaining husbands and wives on the basis of marriage certificates
- The elements we just stored appear in pairs, so we think of Map as a collection of couples.
-
Step analysis
- Gets a collection of all key-value pairs of objects
- Set < Map. Entry < K, V > entrySet (): Gets a collection of all key-value pairs of objects
- Traversing the set of key-value pairs of objects to get each key-value pair of objects
- With enhanced for implementation, get each Map.Entry
- Getting keys and values from key-value pairs of objects
- Get the key with getKey()
- Get the value with getValue()
- Gets a collection of all key-value pairs of objects
-
code implementation
public class MapDemo02 { public static void main(String[] args) { //Creating Collection Objects Map<String, String> map = new HashMap<String, String>(); //Adding elements map.put("Zhang Wuji", "Zhao Min"); map.put("Guo Jing", "Huang Rong"); map.put("Yang Guo", "Little dragon maiden"); //Gets a collection of all key-value pairs of objects Set<Map.Entry<String, String>> entrySet = map.entrySet(); //Traversing the set of key-value pairs of objects to get each key-value pair of objects for (Map.Entry<String, String> me : entrySet) { //Getting keys and values from key-value pairs of objects String key = me.getKey(); String value = me.getValue(); System.out.println(key + "," + value); } } }
1.6 Map Set Case [Application]
The key to 1.6.1 HashMap set exercise is that the String value is Student.
-
Case requirements
Create a HashMap collection with a String key and a Student value. Store three key-value pair elements and traverse them
-
code implementation
-
Student category
public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
-
Test class
/* Demand: Create a HashMap collection with a String key and a Student value. Store three key-value pair elements and traverse them Ideas: 1:Defining student classes 2:Creating HashMap Collection Objects 3:Creating Student Objects 4:Adding students to a collection 5:Ergodic set Mode 1: Key Finding Way 2: Keyvalue to Object Finding Key and Value */ public class HashMapDemo { public static void main(String[] args) { //Creating HashMap Collection Objects HashMap<String, Student> hm = new HashMap<String, Student>(); //Creating Student Objects Student s1 = new Student("Lin Qingxia", 30); Student s2 = new Student("Zhang Manyu", 35); Student s3 = new Student("Wang Zuxian", 33); //Adding students to a collection hm.put("itheima001", s1); hm.put("itheima002", s2); hm.put("itheima003", s3); //Mode 1: Key Finding Set<String> keySet = hm.keySet(); for (String key : keySet) { Student value = hm.get(key); System.out.println(key + "," + value.getName() + "," + value.getAge()); } System.out.println("--------"); //Way 2: Keyvalue to Object Finding Key and Value Set<Map.Entry<String, Student>> entrySet = hm.entrySet(); for (Map.Entry<String, Student> me : entrySet) { String key = me.getKey(); Student value = me.getValue(); System.out.println(key + "," + value.getName() + "," + value.getAge()); } } }
-
The key to the 1.6.2 HashMap set exercise is that the Student value is String
-
Case requirements
- Create a HashMap collection with a Student key and String value. Store multiple elements and traverse them.
- Ask for the uniqueness of the key: If the member variables of the student object have the same values, we consider them the same object.
-
code implementation
-
Student category
public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; if (age != student.age) return false; return name != null ? name.equals(student.name) : student.name == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } }
-
Test class
public class HashMapDemo { public static void main(String[] args) { //Creating HashMap Collection Objects HashMap<Student, String> hm = new HashMap<Student, String>(); //Creating Student Objects Student s1 = new Student("Lin Qingxia", 30); Student s2 = new Student("Zhang Manyu", 35); Student s3 = new Student("Wang Zuxian", 33); Student s4 = new Student("Wang Zuxian", 33); //Adding students to a collection hm.put(s1, "Xi'an"); hm.put(s2, "Wuhan"); hm.put(s3, "Zhengzhou"); hm.put(s4, "Beijing"); //Ergodic set Set<Student> keySet = hm.keySet(); for (Student key : keySet) { String value = hm.get(key); System.out.println(key.getName() + "," + key.getAge() + "," + value); } } }
-
1.6.3 Set Nested ArrayList Nested HashMap
-
Case requirements
- Create an ArrayList collection that stores three elements, each of which is a HashMap
- Each HashMap key and value is String and traversed.
-
code implementation
public class ArrayListIncludeHashMapDemo { public static void main(String[] args) { //Create an ArrayList collection ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>(); //Create a HashMap collection and add key-value pair elements HashMap<String, String> hm1 = new HashMap<String, String>(); hm1.put("Sun CE", "Big Joe"); hm1.put("Zhou Yu", "Little Joe"); //Add HashMap as an element to the ArrayList collection array.add(hm1); HashMap<String, String> hm2 = new HashMap<String, String>(); hm2.put("Guo Jing", "Huang Rong"); hm2.put("Yang Guo", "Little dragon maiden"); //Add HashMap as an element to the ArrayList collection array.add(hm2); HashMap<String, String> hm3 = new HashMap<String, String>(); hm3.put("Linghu Chong", "Ren Yingying"); hm3.put("Lin Pingzhi", "Yue Lingshan"); //Add HashMap as an element to the ArrayList collection array.add(hm3); //Traversing the ArrayList collection for (HashMap<String, String> hm : array) { Set<String> keySet = hm.keySet(); for (String key : keySet) { String value = hm.get(key); System.out.println(key + "," + value); } } } }
1.6.4 nested HashMap nested ArrayList
-
Case requirements
- Create a HashMap collection that stores three key-value pairs of elements, each of which has a String key and an ArrayList value.
- Each ArrayList element is String and traverses.
-
code implementation
public class HashMapIncludeArrayListDemo { public static void main(String[] args) { //Create a HashMap collection HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>(); //Create the ArrayList collection and add elements ArrayList<String> sgyy = new ArrayList<String>(); sgyy.add("Zhuge Liang"); sgyy.add("Zhao Yun"); //Add ArrayList as an element to the HashMap collection hm.put("Romance of the Three Kingdoms",sgyy); ArrayList<String> xyj = new ArrayList<String>(); xyj.add("Tang Seng"); xyj.add("Sun WuKong"); //Add ArrayList as an element to the HashMap collection hm.put("Journey to the West",xyj); ArrayList<String> shz = new ArrayList<String>(); shz.add("Wu Song"); shz.add("Lu Zhishen"); //Add ArrayList as an element to the HashMap collection hm.put("Water Margin",shz); //Traversing HashMap Collection Set<String> keySet = hm.keySet(); for(String key : keySet) { System.out.println(key); ArrayList<String> value = hm.get(key); for(String s : value) { System.out.println("\t" + s); } } } }
1.6.5 Statistics of the number of occurrences of each character in a string
-
Case requirements
- Keyboard input a string, which requires statistics of the number of occurrences of each string in the string.
- Example: keyboard input "aababcabcdabcde" output in console: "a(5)b(4)c(3)d(2)e(1)"
-
code implementation
public class HashMapDemo { public static void main(String[] args) { //Keyboard input a string Scanner sc = new Scanner(System.in); System.out.println("Enter a string:"); String line = sc.nextLine(); //Create a HashMap collection with Character as the key and Integer as the value // HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); TreeMap<Character, Integer> hm = new TreeMap<Character, Integer>(); //Traverse the string to get each character for (int i = 0; i < line.length(); i++) { char key = line.charAt(i); //Take each character as the key to find the corresponding value in the HashMap set and see its return value. Integer value = hm.get(key); if (value == null) { //If the return value is null: indicating that the character does not exist in the HashMap collection, the character is stored as a key and 1 as a value. hm.put(key,1); } else { //If the return value is not null: indicating that the character exists in the HashMap collection, add the value to 1, and then reserve the character and its corresponding value value++; hm.put(key,value); } } //Traverse the HashMap collection, get keys and values, and splice as required StringBuilder sb = new StringBuilder(); Set<Character> keySet = hm.keySet(); for(Character key : keySet) { Integer value = hm.get(key); sb.append(key).append("(").append(value).append(")"); } String result = sb.toString(); //Output results System.out.println(result); } }
2.Collections collection tool class
2.1 Collections Overview and Use [Application]
-
The role of Collections classes
Is a tool class for set operations
-
Common methods of Collections classes
Method name Explain public static void sort(List list) Sort the specified list in ascending order public static void reverse(List<?> list) Reverses the order of elements in the specified list public static void shuffle(List<?> list) Randomize the specified list with the default random source -
Sample code
public class CollectionsDemo01 { public static void main(String[] args) { //Creating Collection Objects List<Integer> list = new ArrayList<Integer>(); //Adding elements list.add(30); list.add(20); list.add(50); list.add(10); list.add(40); //Public static < T extends Comparable <? Super T > void sort (List < T > list): Sort the specified list in ascending order // Collections.sort(list); //Public static void reverse (List <?> list): Reverses the order of elements in the specified list // Collections.reverse(list); //Public static void shuffle (List <?> list): Randomize the specified list using the default random source Collections.shuffle(list); System.out.println(list); } }
2.2ArrayList Collection Stores Students and Sorts [Applications]
-
Case requirements
- ArrayList stores student objects and uses Collections to sort ArrayList
- Requirements: Sort by age from small to large, when the same age, according to the alphabetical order of names
-
code implementation
-
Student category
public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
-
Test class
public class CollectionsDemo02 { public static void main(String[] args) { //Creating ArrayList Collection Objects ArrayList<Student> array = new ArrayList<Student>(); //Creating Student Objects Student s1 = new Student("linqingxia", 30); Student s2 = new Student("zhangmanyu", 35); Student s3 = new Student("wangzuxian", 33); Student s4 = new Student("liuyan", 33); //Adding students to a collection array.add(s1); array.add(s2); array.add(s3); array.add(s4); //Sorting ArrayList collections using Collections //sort(List<T> list, Comparator<? super T> c) Collections.sort(array, new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { //Sort by age from small to large. When the age is the same, sort by alphabetical order of names. int num = s1.getAge() - s2.getAge(); int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num; return num2; } }); //Ergodic set for (Student s : array) { System.out.println(s.getName() + "," + s.getAge()); } } }
-
3. Dou Landlord Case
3.1 Simulated Dou Landlord Case - General Version [Application]
-
Case requirements
The shuffling, licensing and cards watching in the process of fighting landlords are realized through program
-
code implementation
public class PokerDemo { public static void main(String[] args) { //Creating a card box, that is, defining a collection object, is implemented with an ArrayList collection ArrayList<String> array = new ArrayList<String>(); //Install cards in cardboard boxes /* ♦2,♦3,♦4...♦K,♦A ♣2,... ♥2,... ♠2,... Xiao Wang, Big Wang */ //Define a color array String[] colors = {"♦", "♣", "♥", "♠"}; //Define Point Array String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}; for (String color : colors) { for (String number : numbers) { array.add(color + number); } } array.add("Xiao Wang"); array.add("king"); //Shuffling, that is to say, scattering cards, is realized by the shuffle() method of Collections. Collections.shuffle(array); // System.out.println(array); //Licensing, that is, traversing the collection, dealing cards to three players ArrayList<String> lqxArray = new ArrayList<String>(); ArrayList<String> lyArray = new ArrayList<String>(); ArrayList<String> fqyArray = new ArrayList<String>(); ArrayList<String> dpArray = new ArrayList<String>(); for (int i = 0; i < array.size(); i++) { String poker = array.get(i); if (i >= array.size() - 3) { dpArray.add(poker); } else if (i % 3 == 0) { lqxArray.add(poker); } else if (i % 3 == 1) { lyArray.add(poker); } else if (i % 3 == 2) { fqyArray.add(poker); } } //Look at cards, that is, three players traverse their cards separately lookPoker("Lin Qingxia", lqxArray); lookPoker("Liu Yan", lyArray); lookPoker("The wind is clear and clear", fqyArray); lookPoker("A hand", dpArray); } //The Way of Seeing Cards public static void lookPoker(String name, ArrayList<String> array) { System.out.print(name + "The cards are:"); for (String poker : array) { System.out.print(poker + " "); } System.out.println(); } }
3.2 Simulated Dou Landlord Case-Upgraded Version [Application]
-
Case requirements
The shuffling, licensing and cards watching in the process of fighting landlords are realized through the program. Requirement: Sort the cards
-
code implementation
public class PokerDemo { public static void main(String[] args) { //Create HashMap, key is number, value is card HashMap<Integer, String> hm = new HashMap<Integer, String>(); //Create an ArrayList to store the number ArrayList<Integer> array = new ArrayList<Integer>(); //Create colored arrays and point arrays String[] colors = {"♦", "♣", "♥", "♠"}; String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; //Starting from 0, the number is stored in HashMap and the corresponding card is stored. Store numbers in ArrayList at the same time int index = 0; for (String number : numbers) { for (String color : colors) { hm.put(index, color + number); array.add(index); index++; } } hm.put(index, "Xiao Wang"); array.add(index); index++; hm.put(index, "king"); array.add(index); //Shuffle (shuffle number) method of Collections Collections.shuffle(array); //Licensing (issuing is also a number, in order to ensure that the number is sorted, create a TreeSet collection to receive) TreeSet<Integer> lqxSet = new TreeSet<Integer>(); TreeSet<Integer> lySet = new TreeSet<Integer>(); TreeSet<Integer> fqySet = new TreeSet<Integer>(); TreeSet<Integer> dpSet = new TreeSet<Integer>(); for (int i = 0; i < array.size(); i++) { int x = array.get(i); if (i >= array.size() - 3) { dpSet.add(x); } else if (i % 3 == 0) { lqxSet.add(x); } else if (i % 3 == 1) { lySet.add(x); } else if (i % 3 == 2) { fqySet.add(x); } } //Call card reading method lookPoker("Lin Qingxia", lqxSet, hm); lookPoker("Liu Yan", lySet, hm); lookPoker("The wind is clear and clear", fqySet, hm); lookPoker("A hand", dpSet, hm); } //Define a method to look at cards (traverse the TreeSet set, get the number, and go to the HashMap set to find the corresponding cards) public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) { System.out.print(name + "The cards are:"); for (Integer key : ts) { String poker = hm.get(key); System.out.print(poker + " "); } System.out.println(); } }