Article From:

1. Summary:


By looking at the Map interface description, we find the collection under the Map interface and the set under the Collection interface.The form of data storageDifferent, as follows.


1. CollectionMiddleaggregateThe element isIsolated existence(understood as a single), storing elements in the collection.Store by one element


2. MapMiddleaggregateThe element isPairwise existenceA(Understand it as a husband and wife. Each elementThe two part of the key and valueForm,Through keySureFind the corresponding value


3.  CollectionMiddleaggregatecallSet for a single setMapMiddleaggregatecallDouble column set


4. It needs to be noted that the set in MapNo duplicate keys can be includedValue canwithrepeatEach keyonlycanCorresponding to a valueA valueCan correspond toMultiple keys


5.  MapSet in common useHashMapaggregateLinkedHashMapaggregate

Example diagram:



An overview of common sets in the two, Map interface


1. HashMap<K,V>:The hash table structure used for storing data, elementAccess orderCan guaranteeAgreement。Because to ensure that the key is unique and not repeated,Need to rewriteThe hashCode () method of the key and the equals () method

2.  LinkedHashMap<K,V>:HashMapThere is a subclass LinkedHashMap under which data is stored.Hash table structure + chain structure。Through the chain table structure canGuaranteed elementAccess sequence is consistent;The unique and non duplicate keys can be guaranteed by hash table structure.Need to rewriteThe hashCode () method of the key, the equals () method.

Be careful:MapThere are two sets in the interfaceGeneric variable < K, V>stayTime of use,wantFor two generic variablesEndowing data types。Two generic variables < K, V>data typeCan be the same,alsoCan be different

The common methods of three, Map interface

1.put Method:The specified key is corresponding to the value, andAdd to the collection

  MethodThe value of the return is the value corresponding to the key

  When using the put method,If the key is specified(key)stayNot in the collection,There is no value corresponding to this key,Return to nullAnd the specifiedKey values are added to the collectionin

  When using the put method,ifThe specified key (key) is in the collectionexistence,beThe return value isThe value corresponding to the key of the set (the value isThe value before the replacement),AndThe value corresponding to the specified keyreplace withDesignatedNew value

2.getMethod:ObtainThe value (value) corresponding to the specified key (key)

3.removeMethod:according toThe specified key (key) deletes the elementReturnDeleted elementValue (value)


public static void method1(){
        //Create a key set object
        Map<String,String> hm=new HashMap<String,String>();
        //Add element
        hm.put("Huang Xiaoming "," baby "");
        hm.put("Deng Chao "," Sun Li "");
        hm.put("Li Chen "," Fan Bingbing "");
        hm.put("Xu Zheng "," Hong Tao "");
        //Print the value before the coverage
        System.out.println(hm.put("Xu Zheng "," Huang Bo ""));
        //Delete element//hm.remove("Xu Zheng ");//The key is the same, and the previous value is overlaid.//hm.put("Xu Zheng "," Huang Bo ");
        System.out.println(hm.get("Xu Zheng "));

 Four, Map set traversal key finding method


Key finding method:That is to get the value of the key through the key in the element.


Operation steps and diagrams:

   1.Get all the keys in the Map set, becauseThe key is the only oneSo, soReturn to oneSetaggregateStore all the keys


  2.ergodicBondSetaggregate,Get each key

  3.According to the key, getBondvalue



Code demonstration:

public static void method2(){
        //Traversal key finding value
        Map<String,String> hm=new HashMap<String,String>();
        //Add element
        hm.put("Huang Xiaoming "," baby "");
        hm.put("Deng Chao "," Sun Li "");
        hm.put("Li Chen "," Fan Bingbing "");
        hm.put("Xu Zheng "," Hong Tao "");
        //Traversing map//Idea: 1, get the set set with all the keys first//      2、Traversing the set collection to get to each key//      3.Get each value by calling the get method based on the key//    1、Get the set set that has all the keys first
        Set<String> set=hm.keySet();
            // 2、Traversing the set set
        Iterator<String> it=set.iterator();
            //     3.Get each value by calling the get method based on the key
            String st=hm.get(key);


 Five, Entry key values to objects

In the design of the Map class, a nesting is providedInterface:Entry。EntrytakeThe corresponding relationship between key value pairsEncapsulated into objects。That is,Key value pairs,So weWhen traversing the Map set,CanFrom each key value pair(Entry)In the objectGet the corresponding keys and corresponding values


  EntryIt is one provided in the Map interfaceStatic internal nesting interface


1.getKey()Method:Get the Entry objectkey

2.getValue()Method:Get the Entry objectvalue

entrySet()Method:It is used to return all the key value pairs (Entry) objects in the Map collection.Return in the form of Set

Six, MapSet traversal key value pairmode

Key value pairs:That is,adoptIn the collectionEach key value pair (Entry) objectObtainKey value pairs (Entry) objectsKeys and values

Operation steps and diagrams:

    1.Gets all the key value pairs (Entry) objects in the Map collection, and returns them in the form of Set collections.


 2.Traversing the Set collection containing the key value pair (Entry) object, gets each key value pair (Entry) object.

   3.The key and value in the Entry object are obtained through the key value pair (Entry) object.

Note: the Map setYou can’t use iterators or foreach to traverse directly.。howeverTurn to SetafterIt can be usedThat’s right.




 Code demonstration;

public static void method4(){
        Map<String,String> map=new HashMap<String,String>();
        map.put("Lv Bu "," the cool army ");
        map.put(""Zhao Yun", "Shu army");
        map.put("Ludon "," Wu Jun "");
        map.put(""Zhu Geliang", "Shu army");
        //Traversing map//Idea: 1. get a set collection of marriage certificates//       2.Go through the collection of marriage certificates and get every marriage certificate//        3.Get the name and the name of the woman in the marriage certificate after each marriage certificate is obtained.
        Set<Map.Entry<String, String>> set=map.entrySet();
     //Enhanced for loop traversal
//Traverse the marriage certificate// for(Map.Entry<String, String> entry:set){ // //A man's name for a marriage certificate// String key=entry.getKey(); // //A woman's name for a marriage certificate// String value=entry.getValue(); // System.out.println(key+".."+value); // }
      //Iterator traversal
Iterator<Map.Entry<String, String>> it=set.iterator(); while(it.hasNext()){ Map.Entry<String,String>; String key = me.getKey(); String value = me.getValue(); System.out.println(key+".."+value); } }



















Link of this Article: Java learning (Map interface)

Leave a Reply

Your email address will not be published. Required fields are marked *