Map Interface
The Map collection stores data in a key-value pair (Key-value) where the key cannot be duplicated and the value can be duplicated.
Common classes are HashMap, TreeMap and properties
HashMap class
If, now I have a collection that stores a batch of WiFi names and passwords, now requires a quick name to find the password. Such a requirement is very difficult to implement with the list collection, and Java provides us with another form of collection that can solve this problem well. is the map collection.
example: package map.hashmap;import java.util.hashmap;import java.util.map;/** * demo hashset * @author Genius Alliance - Yukun */public class hashmapdemo {public static void main (String[] args) {//Create collection Object Map map = new hashmap ();/* * Note: The map collection adds elements by put, not add * the previous parameter represents key (key), and the latter parameter represents value (value) */ Map.put ("wifiName1", "Password1");/* * when a key repetition occurs, the following value overrides the previous value * and value repeats without affecting the */ Map.put ("wifiName2", "Password2") map.put ("WifiName2", "Password3"); Map.put ("WifiName3", " Password3 ");//Gets the length of the set, joins 4 times, the length is 3int size = map.size (); SYSTEM.OUT.PRINTLN (size);//Get the key "WifiName2" for the valuestring wifi2 = (String) map.get ("wifiName2"); System.out.println (WIFI2);//two ways to convert to a string can be String wifi3 = map.get ("WifiName3"). ToString (); System.out.println (WIFI3);}} Run Result: 3password3password3
Note: The set set will store the added elements on the key of the map collection, and if duplicates do not overwrite, keep the previous one, but when the element in the map collection appears with the same key, Key is not overwritten, but value is overwritten with the value added later.
When we talk about adding elements to the Set collection, we create a node that maintains the currently joined element in the node's key. There is also a Value property in the node, which also holds an object, except that the Value property is not used in set. The map collection needs to store two values, key and value, where the first parameter passed in when we call the put method is stored on the node object's property key, and the second parameter passed in is stored on the Node object's property value.
from this point, when using key to get the corresponding value in the Map collection, first by finding the node object in the hash table where the key is located, and then returning the value of values in the Node object, then we get the value of key.
Map Collection A demonstration of some common methods
Example:package map.hashmap;import java.util.collection;import java.util.hashmap;import java.util.set;/** * demonstrates some common methods in the HashMap class * @author Genius Federation - Yukun */public class hashmapmethoddemo {public static void main (String[] args) {// Create two classes of Class1 and Class2hashmap class1 = new hashmap (); Hashmap class2 = new hashmap ();/* * to two classes to add three students and scores * 1 class there is a classmate called "Harry", Score is 50 * 2 class also has a "Harry" classmate, the results are 90 points */class1.put ("Zhang San", "80 Points") Class1.put ("John Doe", "60 points"); Class1.put ("Harry", "50 Points") class2.put ("Zhao Si", "80 Points") class2.put ("Chen Liu", "0 Points") class2.put ("Harry", " 90 ");//Judge 1 class has no name" Harry "Classmate Boolean containskey = class1.containskey (" Harry "); System.out.println ("There is no key in the set Class1 is Harry:" + containskey); System.out.println ("-------------------------------------");//Judging whether Class 1 has a score of 90 students boolean containsvalue = class1.containsvalUE ("90 points"); System.out.println ("There is no value in the set Class1 is 90 points:" + containsvalue); System.out.println ("-------------------------------------");//merge 2 classmates into a class class1.putall (CLASS2);// Get class number (set length) int size = class1.size (); SYSTEM.OUT.PRINTLN ("Total number of combined classes:" + size); System.out.println ("-------------------------------------");//Get the names of all the students in Class 1 set nameset = Class1.keyset ();//enhanced for loop output all names for (Object o : nameset) {system.out.print (o + " ");} System.out.println (); System.out.println ("-------------------------------------");//Get the results of all students in Class 1 collection scores = Class1.values ();//enhanced for loop output all scores for (object o : scores) {system.out.print (o + " ");} System.out.println (); System.out.println ("-------------------------------------");//Get the names and grades of all students in Class 1 set nameandscoreset = class1.entryset ();//enhanced for loop output all scores for (Object o : nameandscoreset) {systeM.out.print (o + " ");} System.out.println (); System.out.println ("-------------------------------------");//Get Harry's score object wangwuscore = Class1.get ("Harry"); System.out.println ("post-merger Harry Score:" + wangwuscore); System.out.println ("-------------------------------------");//delete the key "Harry" Valueclass1.remove ("Harry");//delete "Harry" After System.out.println ("Harry's Score:" + class1.get ("Harry")); System.out.println ("Does not contain a key called" Harry ":" + class1.containskey ("Harry")); SYSTEM.OUT.PRINTLN ("whether contains" 90 points "of value:" + class1.containsvalue ("90 points")); System.out.println ("-------------------------------------");//replacement of Chen Class1.replace ("Chen Liu", "59 points"); SYSTEM.OUT.PRINTLN ("Replacement of Chen Liu's results:" + class1.get ("Chen Liu")); System.out.println ("-------------------------------------");//empties the set Class1.clear ();//Determines whether the collection is empty System.out.println ( "Clears the collection after the Clear method is empty:" + class1.isempty ());}}
Summarize:
Map is stored in the structure of key-value pairs;
When key is duplicated, the newly added key will not overwrite the original key, but the newly added value will overwrite the value of the original key.
Both key and value can use NULL
Special note: The set set is actually storing the element on the map key. When you create a HashSet object A, a HashMap object map is created at the bottom, and Map.put ("abc", obj) is called when you want to add elements to set set a (A.add ("abc")).
Therefore, the implementation of the set is the way the key is implemented in map (array + single-chain table), because the element storage array subscript is obtained by a specific hash algorithm, so also known as hash storage
The following is the source//Creation HashSet object in HashSet is to create a HashMap object in the underlying public HashSet () {map = new hashmap<> ();} When adding an element to the set collection, the underlying is adding the added element to the key on the map collection, public boolean add (e e) {return Map.put (E, PRESENT) ==null;}
TreeMap class
As the name indicates, its key is the same as TreeSet, and the other properties are the same as HashMap. So this is no longer a detailed story.
Example:package map.treemap;import java.util.set;import java.util.treemap;/** * Demo TreeSet Collection * @author Genius Federation - Yukun */public class treemapdemo { Public static void main (String[] args) {//create three tree objects Branch b1 = new branch (10); Branch b2 = new branch (5); Branch b3 = new branch (8);//Create TreeMap Object Treemap tm = new treemap (); Tm.put (b1, "Branch"), Tm.put (b2, "Branch 5"), Tm.put (b3, "Branch 8");//Get treemap containing all the keys in the collection set ts = tm.keyset ();//Loop Output keyfor (object o : ts) {branch b = (Branch) o;// Output ring System.out.print ("Ring:" + b.getannualring ());//Based on an ordered key, get an orderly valueSystem.out.println (" corresponding value: " + tm.get (b));}}} /** * Branch class branch * The element type that joins the TreeSet collection must implement the comparable interface * the exception will occur when the program is run * @author Genius Alliance - Yukun &NBSP;*/CLASS&NBSP;BRanch implements comparable{//rings: The basis for sorting private int annualring;//with the method Public branch ( int annualring) {this.annualring = annualring;} Override the method in the interface @overridepublic int compareto (object o) {//Force type conversion branch b = ( Branch) o;/* * Use the ring as the basis for sorting comparison * current object ring minus parameter The age * result of the incoming Branch object is equal to 0 for: two branches with the same ring * results greater than 0 means: The current object has a large ring, followed by * the result is less than 0 means: The Parameter object has a large ring, and is in the back */int result = This.annualring - b.annualring;return result;} Get Ring public int getannualring () {return annualring;}} Operation result ring:5 corresponding value: Branch 5 wheel:8 corresponding value: Branch 8 year round:10 corresponding value: Branch 10
Properties Class
Get a key-value pair from a file
File content Format
Key = value
Example: File name: Properties.txt file Contents: username = adminpassword = 123456 File Address: src/map/properties/ Properties.txt where the file address is an instance starting from the project root directory:package map.properties;import java.io.fileinputstream;import java.util.properties;/** * demonstrates some common methods in the Properties class * @author Genius Federation - Yukun * /public class propertiesdemo {public static void main (String[] args) { Create a Properties object Properties p = new properties ();/* * The following code will know what the effect is, and we'll explain later. The purpose of the * try - catch statement is to catch the exception * load method is to load the file * where the parameter is the address of the file */try {p.load (New fileinputstream ("Src/map/properties/properties.txt"));} catch (exception e) {system.out.println ("Loading Error");} Gets the value String username = p.getproperty ("username") corresponding to the username in the file; System.out.println ("User name:" + username);//gets password corresponding value in the file string password = P.getproperty ("password"); SysteM.out.println ("Password:" + password);}} Run Result: User name: admin password: 123456
This article from the "Genius Union Education Official Blog" blog, reproduced please contact the author!
I genius official Free Tutorial 33: Map Collection of the Java Collection framework