18.01 Map collection overview and features
Overview of Map interface: objects that Map keys to values. A mapping cannot contain duplicate keys. Each key can only be mapped to one value at most
Differences between Map interface and Collection interface
1.Map is double column and Collection is single column
2. The key of map is unique, and the subsystem Set of Collection is unique
3. The data structure value of the map set is valid for the key and independent of the value. The data structure of the Collection set is valid for the element
18.02 function overview of map set
Member method:
Optionally, associate the specified value with the specified key in this mapping.
If there is a mapping relationship for a key, remove it from this mapping (optional).
3.void clear():
Optionally, remove all mapping relationships from this mapping.
4.boolean containsKey(Object key):
Returns true if the mapping contains a mapping relationship for the specified key.
5.boolean containsValue(Object value):
Returns true if the mapping maps one or more keys to the specified value.
6.boolean isEmpty():
Returns true if the mapping does not contain a key value mapping relationship.
7.int size():
Returns the number of key value mapping relationships in this mapping.
Returns the value mapped by the specified key; null if the mapping does not contain a mapping relationship for the key.
Returns the name of the key contained in this map Set View.
10.Collection<V> values()
Returns the value contained in this map Collection View.
11.Set<Map.Entry<K,V>> entrySet()
Returns the of the mapping relationships contained in this mapping Set View.
18.03 basic function test of map set
map.put("001", "Wangcai"); : store the element directly for the first time and return null
map.put("001", "Xiaoqiang"); : This is not the first storage. Replace the previous value with a new value and return the previous value
map.remove("001"); : deletes the key value pair element according to the key and returns the value corresponding to the key. If there is no key, it returns null
18.04 acquisition function test of map set
1 Map<String, String> map = new HashMap<String, String>(); 2 3 map.put("001", "Xiao Ming"); 4 map.put("002", "Wangcai"); 5 map.put("003", "cockroach"); 6 //Get value according to key 7 System.out.println(map.get("002"));//Wangcai, return null without this key 8 System.out.println("-----"); 9 //Gets the collection of all keys in the collection 10 Set<String> set = map.keySet(); 11 for(String key : set) 12 { 13 System.out.println(key); 14 } 15 System.out.println("-----"); 16 //Gets the collection of all values in the collection 17 Collection<String> coll = map.values(); 18 for(String value : coll) 19 { 20 System.out.println(value); 21 }
18.05 value finding of traversal key of map set
Find value according to key:
Get the set of all keys, traverse the set of keys, get each key, and find the value according to the key
1 Map<String, String> map = new HashMap<String, String>(); 2 map.put("001", "Xiao Ming"); 3 map.put("002", "Wangcai"); 4 map.put("003", "cockroach"); 5 6 //Get all keys 7 Set<String> set = map.keySet(); 8 for(String key : set) 9 { 10 //Find value according to key 11 String value = map.get(key); 12 System.out.println(key+":"+value); 13 }
18.06 finding keys and values for objects by traversing the key values of the map set
Find keys and values for objects according to key values:
Get the set of all key value pair objects, traverse the set of key value pair objects, get each key value pair object, and find the key and value according to the key value pair object
1 Map<String, String> map = new HashMap<String, String>(); 2 map.put("001", "Xiao Ming"); 3 map.put("002", "Wangcai"); 4 map.put("003", "cockroach"); 5 //Gets a collection of all key value pair objects 6 Set<Map.Entry<String, String>> set = map.entrySet(); 7 //Traverse the collection of key value pair objects to obtain each key value pair object 8 for(Map.Entry<String, String> me : set) 9 { 10 //Get keys and values for objects based on key values 11 String key = me.getKey(); 12 String value = me.getValue(); 13 System.out.println(key+":"+value); 14 }
18.07 comparison diagram of two ways of traversing map set
18.08 the HashMap set key is a case where the Stirng value is String
HashMap class overview: the key is a hash table structure, which can ensure the uniqueness of the key
1 HashMap<String, String> map = new HashMap<String, String>(); 2 3 map.put("001", "Xiao Ming"); 4 map.put("002", "Wangcai"); 5 map.put("003", "cockroach"); 6 map.put("004", "Xiao Hong"); 7 Set<String> set = map.keySet(); 8 for(String key : set) 9 { 10 String value = map.get(key); 11 System.out.println(key+"--"+value); 12 }
18.09 the HashMap set key is a case where the Student value is String
1 // Create collection object 2 HashMap<Student, String> hm = new HashMap<Student, String>(); 3 4 hm.put(new Student("Xiao Ming",23), "001"); 5 hm.put(new Student("cockroach",15), "002"); 6 hm.put(new Student("Wangcai",13), "003"); 7 hm.put(new Student("Zhang San",17), "004"); 8 hm.put(new Student("cockroach",15), "005"); 9 10 // ergodic 11 Set<Student> set = hm.keySet(); 12 for (Student key : set) 13 { 14 String value = hm.get(key); 15 System.out.println(key.getName() + "---" + key.getAge() + "---" 16 + value); 17 }
When the key is a custom object, you need to override the hashCode() and equals() methods
18.10 overview and use of LinkedHashMap
The hash table and link list implementation of the Map interface has a predictable iterative order.
The uniqueness of the key is guaranteed by the hash table
The order of keys is guaranteed by the linked list
1 LinkedHashMap<String, String> hm = new LinkedHashMap<String,String>(); 2 3 // Create and add elements 4 hm.put("2345", "hello"); 5 hm.put("1234", "world"); 6 hm.put("3456", "java"); 7 hm.put("1234", "javaee"); 8 hm.put("3456", "android"); 9 10 // ergodic 11 Set<String> set = hm.keySet(); 12 for (String key : set) 13 { 14 String value = hm.get(key); 15 System.out.println(key + "---" + value); 16 }
Operation results:
2345---hello 1234---javaee 3456---android
18.11 cases where the treemap set key is String and the value is String
Overview of TreeMap class: the key is a red black tree structure, which can ensure the sorting and uniqueness of the key
1 // Create collection object 2 TreeMap<String, String> tm = new TreeMap<String, String>(); 3 4 // Create and add elements 5 tm.put("hello", "Hello"); 6 tm.put("world", "world"); 7 tm.put("java", "Java"); 8 tm.put("world", "World 2"); 9 tm.put("javaee", "Java EE"); 10 11 // Traversal set 12 Set<String> set = tm.keySet(); 13 for (String key : set) 14 { 15 String value = tm.get(key); 16 System.out.println(key + "---" + value); 17 }
Operation results:
hello---Hello java---Java javaee---Java EE world---World 2
18.12 the treemap set key is a case where the Student value is String
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Create collection object 6 TreeMap<Student, String> tm = new TreeMap<Student, String>(new Comparator<Student>() 7 { 8 @Override 9 public int compare(Student s1, Student s2) 10 { 11 // Main conditions 12 int num = s1.getAge() - s2.getAge(); 13 // minor criteria 14 int num2 = num == 0 ? s1.getName().compareTo( 15 s2.getName()) : num; 16 return num2; 17 } 18 }); 19 20 tm.put(new Student("Xiao Ming",23), "001"); 21 tm.put(new Student("cockroach",15), "002"); 22 tm.put(new Student("Wangcai",13), "003"); 23 tm.put(new Student("Zhang San",17), "004"); 24 tm.put(new Student("cockroach",15), "005"); 25 26 Set<Map.Entry<Student, String>> set = tm.entrySet(); 27 for(Map.Entry<Student, String> me : set) 28 { 29 Student key = me.getKey(); 30 String value = me.getValue(); 31 System.out.println(key.getName()+":"+key.getAge()+":"+value); 32 } 33 } 34 }
Operation results:
Wangcai:13:003 cockroach:15:005 Zhang San:17:004 Xiao Ming:23:001
18.13 statistics of the number of occurrences of each character in the string case diagram
"Aababcabcdcabcde" to obtain the required result of the number of occurrences of each letter in the string: a(5)b(4)c(3)d(2)e(1)
18.14 count the number of occurrences of each character in the string case code implementation
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Define a string (improved for keyboard entry) 6 Scanner sc = new Scanner(System.in); 7 System.out.println("Please enter a string:"); 8 String line = sc.nextLine(); 9 10 // Define a TreeMap collection 11 TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>(); 12 13 //Convert string to character array 14 char[] chs = line.toCharArray(); 15 16 //Traverse the character array to get each character 17 for(char ch : chs) 18 { 19 //Take the character just obtained as the key to find the value in the set and see the return value 20 Integer i = tm.get(ch); 21 22 //Is null: if the key does not exist, the character is stored as a key and 1 as a value 23 if(i == null) 24 { 25 tm.put(ch, 1); 26 } 27 else 28 { 29 //Not null: if the key exists, add 1 to the value, and then rewrite to store the key and value 30 i++; 31 tm.put(ch,i); 32 } 33 } 34 35 //Define string buffer variables 36 StringBuilder sb= new StringBuilder(); 37 38 //Traverse the set, get the keys and values, and splice them as required 39 Set<Character> set = tm.keySet(); 40 for(Character key : set) 41 { 42 Integer value = tm.get(key); 43 sb.append(key).append("(").append(value).append(")"); 44 } 45 46 //Convert string buffer to string output 47 String result = sb.toString(); 48 System.out.println("result:"+result); 49 } 50 }
Operation results:
Please enter a string: aasdgrfedcsdf result:a(2)c(1)d(3)e(1)f(2)g(1)r(1)s(2)
18.15 case of HashMap set nesting HashMap set
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Large collection object 6 HashMap<String, HashMap<String, Integer>> bigMap = new HashMap<String, HashMap<String, Integer>>(); 7 8 // Collection object 1 9 HashMap<String, Integer> hm1 = new HashMap<String, Integer>(); 10 // Add element 11 hm1.put("Xiao Ming", 20); 12 hm1.put("cockroach", 22); 13 // Add collection to large collection 14 bigMap.put("Set 1", hm1); 15 16 // Collection object 2 17 HashMap<String, Integer> hm2 = new HashMap<String, Integer>(); 18 // Add element 19 hm2.put("Wangcai", 5); 20 hm2.put("Zhang San", 23); 21 // Add collection to large collection 22 bigMap.put("Set 2", hm2); 23 24 //Traversal set 25 Set<String> bigMapset = bigMap.keySet(); 26 for(String bigMapKey : bigMapset) 27 { 28 System.out.println(bigMapKey); 29 HashMap<String, Integer> value = bigMap.get(bigMapKey); 30 Set<String> set = value.keySet(); 31 for(String s : set) 32 { 33 Integer i = value.get(s); 34 System.out.println("\t"+s+":"+i); 35 } 36 } 37 } 38 }
Operation results:
Set 1 cockroach:22 Xiao Ming:20 Set 2 Wangcai:5 Zhang San:23
18.16 code embodiment of multi-layer nesting of sets
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Create a large collection 6 HashMap<String, HashMap<String, ArrayList<Student>>> czbkMap = new HashMap<String, HashMap<String, ArrayList<Student>>>(); 7 8 // Beijing Campus Data 9 HashMap<String, ArrayList<Student>> bjCzbkMap = new HashMap<String, ArrayList<Student>>(); 10 ArrayList<Student> array1 = new ArrayList<Student>(); 11 Student s1 = new Student("Lin Qingxia", 27); 12 Student s2 = new Student("Breezy", 30); 13 array1.add(s1); 14 array1.add(s2); 15 ArrayList<Student> array2 = new ArrayList<Student>(); 16 Student s3 = new Student("Zhao Yazhi", 28); 17 Student s4 = new Student("Wu Xin", 29); 18 array2.add(s3); 19 array2.add(s4); 20 bjCzbkMap.put("Basic class", array1); 21 bjCzbkMap.put("Employment class", array2); 22 czbkMap.put("Beijing Campus", bjCzbkMap); 23 24 // Xi'an campus data 25 HashMap<String, ArrayList<Student>> xaCzbkMap = new HashMap<String, ArrayList<Student>>(); 26 ArrayList<Student> array3 = new ArrayList<Student>(); 27 Student s5 = new Student("Fan Bingbing", 27); 28 Student s6 = new Student("Liu ", 30); 29 array3.add(s5); 30 array3.add(s6); 31 ArrayList<Student> array4 = new ArrayList<Student>(); 32 Student s7 = new Student("Bing Bing Li", 28); 33 Student s8 = new Student("Zhang Zhihao", 29); 34 array4.add(s7); 35 array4.add(s8); 36 xaCzbkMap.put("Basic class", array3); 37 xaCzbkMap.put("Employment class", array4); 38 czbkMap.put("Xi'an Campus", xaCzbkMap); 39 40 // Traversal set 41 Set<String> czbkMapSet = czbkMap.keySet(); 42 for (String czbkMapKey : czbkMapSet) 43 { 44 System.out.println(czbkMapKey); 45 HashMap<String, ArrayList<Student>> czbkMapValue = czbkMap.get(czbkMapKey); 46 Set<String> czbkMapValueSet = czbkMapValue.keySet(); 47 for (String czbkMapValueKey : czbkMapValueSet) 48 { 49 System.out.println("\t" + czbkMapValueKey); 50 ArrayList<Student> czbkMapValueValue = czbkMapValue.get(czbkMapValueKey); 51 for (Student s : czbkMapValueValue) 52 { 53 System.out.println("\t\t" + s.getName() + "---"+ s.getAge()); 54 } 55 } 56 } 57 } 58 }
Operation results:
Beijing Campus Employment class Zhao Yazhi---28 Wu Xin---29 Basic class Lin Qingxia---27 Breezy---30 Xi'an Campus Employment class Bing Bing Li---28 Zhang Zhihao---29 Basic class Fan Bingbing---27 Liu ---30
18.17 differences between HashMap and Hashtable
1: The difference between hashtable and HashMap
Hashtable: thread safe and inefficient. Null keys and null values are not allowed
HashMap: thread is unsafe and efficient. Allow null keys and null values
2: Do list, set, Map and other interfaces inherit the sub Map interface?
List and Set do not inherit from the Map interface, they inherit from the Collection interface
The Map interface itself is a top-level interface
18.18 overview of collections tool class
Collections class overview: tool classes for collection operations are static methods
Differences between Collections and Collection s:
Collection: is the top-level interface of a single column collection, with sub interfaces List and Set.
Collections: is a tool class for collection operations. It has methods for sorting and binary search of collections
18.19 explanation of common methods of collections tool class
Collections member method
1.public static <T extends Comparable<? super T>> void sort(List<T> list):
Sorts the specified list in ascending order according to the natural order of the elements.
2.public static <T> int binarySearch(List<? extends Comparable<? super T>> list,T key):
Use the binary search method to search the specified list to obtain the specified object.
3.public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll):
Returns the largest element of a given collection according to the natural order of elements.
4.public static void reverse(List<?> list):
Reverses the order of the elements in the specified list.
5.public static void shuffle(List<?> list):
Replaces the specified list with the default random source. All permutations are approximately equal in probability.
Example:
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Create collection object 6 List<Integer> list = new ArrayList<Integer>(); 7 8 // Add element 9 list.add(30); 10 list.add(20); 11 list.add(50); 12 list.add(10); 13 list.add(40); 14 15 System.out.println("original:" + list); 16 //Sorting is natural by default 17 Collections.sort(list); 18 System.out.println("sort:" + list); 19 // Binary search 20 System.out.println("lookup:"+Collections.binarySearch(list, 30)); 21 // Maximum 22 System.out.println("Maximum:"+Collections.max(list)); 23 // reversal 24 Collections.reverse(list); 25 System.out.println("reversal:" + list); 26 //Random permutation 27 Collections.shuffle(list); 28 System.out.println("random:" + list); 29 } 30 }
Operation results:
original:[30, 20, 50, 10, 40] sort:[10, 20, 30, 40, 50] lookup:2 Maximum:50 reversal:[50, 40, 30, 20, 10] random:[20, 10, 30, 50, 40]
18.20 ArrayList stores custom objects and sorts cases
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Create collection object 6 List<Student> list = new ArrayList<Student>(); 7 8 // Create student object 9 Student s1 = new Student("Xiao Ming", 27); 10 Student s2 = new Student("Wangcai", 30); 11 Student s3 = new Student("cockroach", 28); 12 Student s4 = new Student("Zhang San", 29); 13 14 // Add element object 15 list.add(s1); 16 list.add(s2); 17 list.add(s3); 18 list.add(s4); 19 20 // sort 21 // Natural sorting must implement the Comparable interface 22 //Collections.sort(list); 23 // Comparator sort 24 // If there are both natural sorting and comparator sorting, comparator sorting shall prevail 25 Collections.sort(list, new Comparator<Student>() 26 { 27 @Override 28 public int compare(Student s1, Student s2) 29 { 30 int num = s2.getAge() - s1.getAge(); 31 int num2 = num == 0 ? s1.getName().compareTo(s2.getName()): num; 32 return num2; 33 } 34 }); 35 // Traversal set 36 for (Student s : list) 37 { 38 System.out.println(s.getName() + "---" + s.getAge()); 39 } 40 } 41 }
Operation results:
Wangcai---30 Zhang San---29 cockroach---28 Xiao Ming---27
18.21 simulated landlords shuffle and deal cards
Simulated landlords shuffle and deal cards
analysis:
A: Create a card box, B: pack, C: shuffle, D: deal, E: watch
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Create a card box 6 ArrayList<String> array = new ArrayList<String>(); 7 8 // Define an array of decors 9 String[] colors = { "♠", "♥", "♣", "♦" }; 10 // Define an array of points 11 String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", 12 "J", "Q", "K" }; 13 // Deck 14 for (String color : colors) 15 { 16 for (String number : numbers) 17 { 18 array.add(color.concat(number)); 19 } 20 } 21 array.add("Xiao Wang"); 22 array.add("king"); 23 24 // shuffle the cards 25 Collections.shuffle(array); 26 27 // System.out.println("array:" + array); 28 29 // Licensing 30 ArrayList<String> player1 = new ArrayList<String>(); 31 ArrayList<String> player2 = new ArrayList<String>(); 32 ArrayList<String> player3 = new ArrayList<String>(); 33 ArrayList<String> diPai = new ArrayList<String>(); 34 35 for (int x = 0; x < array.size(); x++) 36 { 37 if (x >= array.size() - 3) 38 { 39 diPai.add(array.get(x)); 40 } 41 else if (x % 3 == 0) 42 { 43 player1.add(array.get(x)); 44 } 45 else if (x % 3 == 1) 46 { 47 player2.add(array.get(x)); 48 } 49 else if (x % 3 == 2) 50 { 51 player3.add(array.get(x)); 52 } 53 } 54 55 // Look at the cards 56 lookPoker("Player 1", player1); 57 lookPoker("Player 2", player2); 58 lookPoker("Player 3", player3); 59 60 lookPoker("a hand", diPai); 61 } 62 63 public static void lookPoker(String name, ArrayList<String> array) 64 { 65 System.out.print(name + "Your card is:"); 66 for (String s : array) 67 { 68 System.out.print(s + " "); 69 } 70 System.out.println(); 71 } 72 }
Operation results:
Player 1's card is:♦10 ♥4 ♠K ♠5 ♦6 ♥K ♦8 ♥2 ♥3 ♣8 ♣3 ♣4 ♦7 ♠Q ♣10 ♠3 ♠6 Player 2's card is:♦9 ♦5 ♦A ♣5 ♦3 ♥8 ♣2 ♥J ♦J ♥5 ♦4 ♠9 ♠10 Xiao Wang♣A ♥Q ♥7 Player 3's card is:♠A ♣6 ♦2 ♦K ♣9 ♣K ♣7 ♦Q ♠4 ♥9 ♠7 king♣Q ♥10 ♠8 ♣J ♠2 What's the card:♥A ♥6 ♠J
18.22 code implementation of simulating landlords' shuffling and licensing and sorting cards
Idea:
A: Create a HashMap collection
B: Create an ArrayList collection
C: Create Decor array and point array
D: Start from 0, store the number in the HashMap, store the corresponding card, and store the number in the ArrayList at the same time.
E: Shuffle (shuffle the number)
F: Licensing (the licensing is also numbered. In order to ensure that the numbers are sorted, create a TreeSet set to receive)
G: Watch cards (traverse the TreeSet set, get the number, and find the corresponding card in the HashMap set)
1 public class Practice 2 { 3 public static void main(String[] args) 4 { 5 // Create a HashMap collection 6 HashMap<Integer, String> hm = new HashMap<Integer, String>(); 7 8 // Create an ArrayList collection 9 ArrayList<Integer> array = new ArrayList<Integer>(); 10 11 // Create Decor array and point array 12 // Define an array of decors 13 String[] colors = { "♠", "♥", "♣", "♦" }; 14 // Define an array of points 15 String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", 16 "K", "A", "2", }; 17 18 // Start from 0, store the number in the HashMap, store the corresponding card, and store the number in the ArrayList at the same time. 19 int index = 0; 20 21 for (String number : numbers) 22 { 23 for (String color : colors) 24 { 25 String poker = color.concat(number); 26 hm.put(index, poker); 27 array.add(index); 28 index++; 29 } 30 } 31 hm.put(index, "Xiao Wang"); 32 array.add(index); 33 index++; 34 hm.put(index, "king"); 35 array.add(index); 36 37 // Shuffle (shuffle the number) 38 Collections.shuffle(array); 39 40 // Licensing (the licensing is also numbered. In order to ensure that the numbers are sorted, create a TreeSet set to receive) 41 TreeSet<Integer> player1 = new TreeSet<Integer>(); 42 TreeSet<Integer> player2 = new TreeSet<Integer>(); 43 TreeSet<Integer> player3 = new TreeSet<Integer>(); 44 TreeSet<Integer> diPai = new TreeSet<Integer>(); 45 46 for (int x = 0; x < array.size(); x++) 47 { 48 if (x >= array.size() - 3) 49 { 50 diPai.add(array.get(x)); 51 } else if (x % 3 == 0) 52 { 53 player1.add(array.get(x)); 54 } else if (x % 3 == 1) 55 { 56 player2.add(array.get(x)); 57 } else if (x % 3 == 2) 58 { 59 player3.add(array.get(x)); 60 } 61 } 62 63 // Watch cards (traverse the TreeSet set, get the number, and find the corresponding card in the HashMap set) 64 lookPoker("Player 1", player1, hm); 65 lookPoker("Player 2", player2, hm); 66 lookPoker("Player 3", player3, hm); 67 lookPoker("a hand", diPai, hm); 68 } 69 70 // Function of writing and watching cards 71 public static void lookPoker(String name, TreeSet<Integer> ts, 72 HashMap<Integer, String> hm) 73 { 74 System.out.print(name + "Your card is:"); 75 for (Integer key : ts) 76 { 77 String value = hm.get(key); 78 System.out.print(value + " "); 79 } 80 System.out.println(); 81 } 82 }
Operation results:
Player 1's card is:♠3 ♦3 ♥4 ♣4 ♥5 ♣5 ♠6 ♣8 ♥9 ♦10 ♥J ♣J ♦Q ♣A ♠2 ♣2 king Player 2's card is:♠5 ♦5 ♣7 ♦7 ♠9 ♥10 ♦J ♠Q ♣Q ♠K ♣K ♠A ♥A ♦A ♥2 ♦2 Xiao Wang Player 3's card is:♥3 ♣3 ♠4 ♦4 ♥6 ♣6 ♠7 ♥7 ♥8 ♦8 ♣9 ♠10 ♣10 ♠J ♥Q ♥K ♦K What's the card:♦6 ♠8 ♦9