Two column set
(1) Common functions of Map interface
1. Overview
Map < K, V > is a generic interface, which is the top-level interface of the two column set, and defines the functions and traversal methods of all the two column sets
Double column set: it is a container used to store data of multiple key value pairs. Double column: one column is a key and the other column is a value. Keys and values appear in pairs.
Map Chinese here is the meaning of mapping
Key Value pair: a pair of data in a one-to-one mapping relationship. Mapping means that one Value can find another Value. In the Map set, it means that the Value can be found through the key Value
2. Map storage key value pair characteristics
① It stores key value pair data
② Unordered set
③ The key must be unique. The key value cannot be repeated, and the value value can be repeated.
3. Common methods in Map interface
import java.util.HashMap; import java.util.Map; public class Demo01 { public static void main(String[] args) { Map<String,String> map = new HashMap<>(); map.put("name","fsf"); map.put("age","19"); //add to map.put("gender","man"); System.out.println(map); map.put("name","tom"); System.out.println(map); //delete //Returns the deleted element System.out.println(map.remove("name")); //Get the corresponding value System.out.println(map.get("gender")); //Include a key System.out.println(map.containsKey("aaa")); //Determine whether a Value is included System.out.println(map.containsValue("19")); //Returns the number of elements System.out.println(map.size()); //empty map.clear(); //Judge whether it is empty System.out.println(map.isEmpty()); } }
(2) Traversal mode of Map collection
1. Key traversal (key value finding traversal)
The Map set cannot be traversed directly. The Map set is transformed into a single column set (a single column set storing all the key values). The key value pair data of the Map set is obtained indirectly by traversing the single column set
method:
keySet(): get all the keys to form a set
get (K key): obtain the corresponding value through the key
Steps:
① Get all the keys in the Map set through the keySet method and store them in the set
② Traverse the set set to get each key value
③ Map set get (K key) to get the corresponding value
code:
import java.util.HashMap; import java.util.Map; import java.util.Set; public class Demo01 { public static void main(String[] args) { Map<String,Integer> map = new HashMap<>(); map.put("max",100); map.put("mid",50); map.put("min",30); Set<String> keys = map.keySet(); System.out.println(keys); for (String key : keys) { System.out.println(key+"=="+map.get(key)); } } }
2. Value traversal (not map traversal)
Method: values (): you can get all the values in the set to form a separate set
You can only get all the values. You can't find the corresponding key through the value. You can only get the value of the map. You can't traverse the key value pair
import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Demo02 { public static void main(String[] args) { Map<String,String> map = new HashMap<>(); map.put("1","Zhang San"); map.put("2","Li Si"); map.put("3","Wang Wu"); map.put("4","Zhao Liu"); Collection<String> c = map.values(); for (String s : c) { System.out.println(s); } } }
3. Key value pair traversal
method:
entrySet (): the method of converting each key value pair of the double column set into an Entry object, and then putting the Entry into the set set ----- the Map set
Entry is an interface defined inside the Map interface. We don't need to care about how to generate the interface implementation class and call the Map collection The entrySet method generates an entry interface implementation class object according to the key value pair.
Method of Entry object:
getKey(): get the key value of the Entry object (actually the key value of the Map object) ------ Entry interface method
getValue (): get the value of the Entry object (actually the value of the map collection) -- the method of the Entry interface
Steps:
① The map Set is transformed into the Set set of Entry objects through the entrySet method
② Traverse the Set set to get each Entry object
③ Get the key value and value value respectively through the getKey and getValue methods of Entry
import java.util.HashMap; import java.util.Map; import java.util.Set; public class Demo03 { public static void main(String[] args) { Map<String,String> map = new HashMap<>(); map.put("1","Zhang San"); map.put("2","Li Si"); map.put("3","Wang Wu"); map.put("4","Zhao Liu"); //Call entrySet() to return the data stored in a Set set and encapsulate it into an entry object according to the key value of the Map Set Set<Map.Entry<String, String>> set = map.entrySet(); //Traverse set set for (Map.Entry<String, String> en : set) { String key = en.getKey(); String value = en.getValue(); System.out.println(key+"==="+value); } } }
(3) Introduction to common implementation classes of Map
HashMap < K, V >: the hash table structure is used to store data, and the access order of elements cannot be guaranteed to be consistent.
To ensure the uniqueness and non repetition of the Key, if the user-defined type data is used as the Key value, the hashCode () method and equals () method of the Key need to be rewritten to ensure the uniqueness and non repetition. JDK provides types that do not need to be overridden.
The difference between HashMap and Hashtable
1. The timing is different
HashMap appears in jdk1.2
Hashtable is jdk1.0
2. Thread safety is different
HashMap is thread unsafe
Hashtable is thread safe
3. Different efficiency
HashMap is efficient
Hashtable is thread safe
4. Different requirements for storing data
HashMap supports null values and null keys
Hashtable does not support null data
5. HashMap and Hashtable have the same API.
Relationship between HashMap and HashSet
The bottom layer of HashSet is built by HashMap
The unique principle of the stored value element of HashSet is the unique principle of the stored key value of HashMap
When you create a HashSet set, you actually create a HashMap set
When the add method of the HashSet set adds elements, the bottom layer calls the put method of the HashMap to add them to the Map set
When adding, if the key has been stored in the HashMap, the value value in the newly added key value pair will be used to overwrite the original key value value
practice:
Enter a string on the keyboard and count the number of occurrences of each character
For example: enter aaaabbccddd!@#@#$@#$%cc66ff
Print out: a yes four Number, b yes two Number, c yes four Number, d yes three One,! yes one One@ yes three One$ yes two Number,% yes one 6, 6 yes 2, f yes two individual
package com.offcn.demo03; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; public class Demo01 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); HashMap<Character,Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { if(map.containsKey(s.charAt(i))){ Integer a = map.get(s.charAt(i)); a++; map.put(s.charAt(i),a); }else { map.put(s.charAt(i),1); } } StringBuilder sb = new StringBuilder(); for (Map.Entry<Character,Integer> en : map.entrySet()){ sb.append(en.getKey()+"yes").append(en.getValue()+"individual"); } System.out.println(sb); } }
LinkedHashMap
LinkedHashMap < K, V >: there is a subclass LinkedHashMap under HashMap, which uses hash table structure + linked list structure to store data. Through the linked list structure, the access order of elements can be ensured to be consistent; The hash table structure can ensure that the key is unique and not repeated, and the key needs to be rewritten
hashCode() method, equals() method.
Features: an ordered Map collection with unique key values can be stored, and the key value is null
import java.util.LinkedHashMap; public class Demo01 { public static void main(String[] args) { LinkedHashMap<String,String> map = new LinkedHashMap<>(); map.put("1","Zhang San"); map.put("2","Li Si"); map.put("3","Wang Wu"); map.put("3","Zhao Liu"); map.put(null,null); System.out.println(map); } }
TreeMap (understand)
The collection can be sorted according to the natural order of the key values of the stored key value pairs, or according to the Comparator provided when creating the Map collection, depending on the construction method used.
Natural sorting: the type of key should implement the Comparable interface
Comparator sorting: creating a TreeMap object is to pass in a comparator and sort the key s according to the rules of the comparator
Collections tool class
(1) Use and precautions of variable parameters
1. Overview
Variable parameters are also called variable number of parameters. If they are used as formal parameters of a method, the number of method parameters is variable,
Usage scenario: the parameter type of the method has been determined, and the number is uncertain. We can use variable parameters
[parameter list deformation of methods with multiple formal parameters of the same type] (int a, int b, int c, int d,) -- > (int... A)
2. Format
Modifier return value type method name (data type 1, parameter name 1, data type 2, parameter name 2, data type n... Parameter name n){
The variable parameter name is in the method body, and it is operated as an array name
}
When calling a method with variable parameters, 0~n arguments can be passed in to assign values to the variable parameters
3. Precautions
1. The variable parameter name here is actually an array name
2. If a method has multiple parameters, including variable parameters, the variable parameters should be placed last, otherwise the compilation will report an error
3. Only one variable parameter can be used in a method, otherwise the compilation will report an error
package com.offcn.demo05; public class Demo01 { public static void main(String[] args) { System.out.println(getSum(10,10,10,10,10,10,10)); printNum(1.0,2.0f,1,2,3,4,5); } public static int getSum(int... a){ int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } public static void printNum(double a,float b,int... c){ System.out.println(a); System.out.println(b); for (int i = 0; i < c.length; i++) { System.out.println(c[i]); } } }
(2) Collections common features
1. Overview
Collections class is a tool class that encapsulates many common methods of operating collections. It can operate not only single column collections, but also double column collections
1. Cannot create object
2. The contents in the class are static (static attributes and static methods)
2. Common methods
package com.offcn.demo05; import java.util.ArrayList; import java.util.Collections; public class Demo02 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(100); list.add(59); list.add(10); list.add(79); list.add(15); list.add(45); System.out.println(list); Collections.sort(list); System.out.println(list); Collections.reverse(list); System.out.println(list); Collections.shuffle(list); System.out.println(list); } }