Map two column set

Learning objectives

  • Be able to tell the characteristics of Map set
  • Save data using the Map collection add method
  • Use the key to find value method to traverse the Map collection
  • Traverse the Map collection using key value pairs
  • HashMap can be used to store data of user-defined key value pairs
  • Be able to use HashMap to write cases of landlords shuffling and licensing

1. Map two column set: unordered, binding values through keys, corresponding relationships, and unique keys

1.1 general

  • The one-to-one correspondence is called mapping map

  • Java provides a special collection class to store the corresponding object, namely Java util. Map interface

  • The Collection under the Map interface is different from the Collection interface in the form of storing data, as shown in the following figure:

  • For the Collection in the Collection, the elements exist in isolation (understood as single), and the elements stored in the Collection are stored in the way of elements one by one
  • The collection elements in the Map exist in pairs (understood as husband and wife). Each element consists of two parts: key and value. The corresponding value can be found through the key
  • Collections in the Collection are called single column collections, and collections in the Map are called double column collections
  • It should be noted that the set in the Map cannot contain duplicate keys; The value can be repeated; Each key can only correspond to one value

1.2 common subclasses of map

The Map interface description has several subclasses, including HashMap set and LinkedHashMap set

  • 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 keys, you need to rewrite the hashCode() method and equals() method of keys. (this is also the underlying de duplication principle of yesterday's HashSet)
  • LinkedHashMap<K,V>:
    • There is a subclass LinkedHashMap under HashMap, and the storage data adopts hash table structure + linked list structure
    • Through the linked list structure, the access order of elements can be ensured to be consistent
    • The hash table structure can ensure the uniqueness and non repetition of * * keys. It is necessary to rewrite the hashCode() method and equals() method of * * keys

Tips: the set in the Map interface has two generic variables < K, V >. When used, the data types should be assigned to the two generic variables

The data types of two generic variables < K, V > can be the same or different. key and value can only be reference data types. Generic requirements

1.3 common methods of map interface

Many methods are defined in the Map interface. The common methods are as follows:

  • public V put(K key, V value):
    • Adds the specified key and specified value to the Map collection
    • Adding is also it, changing is also it, the key is unique, the value is overwritten, the overwritten old value is returned if there is coverage, and null is returned if there is no coverage
  • public V remove(Object key):
    • Delete the key value pair element corresponding to the specified key in the Map set and return the value of the deleted element.
  • public V get(Object key):
    • Obtain the corresponding value in the Map collection according to the specified key. If there is no key or value, bind and return null
  • public Set<K> keySet():
    • Get all the keys in the Map collection and store them in the Set collection. A collection of keys
  • public Set<Map.Entry<K,V>> entrySet():
    • Get the collection of all key value pair objects in the Map collection (Set collection)
    • That is, the set of objects of key value pair class. It stores each key value pair object, simulates the key value pair, and obtains the method of each key and value. The key value pair class writes the simulated key value pair, which is composed of keys and values. Naturally, you can obtain the key and the method of obtaining the value

Method demonstration of Map interface

//Create a hashmap object and define key as String type and value as String type
HashMap<String,String> hashMap = new HashMap();
//Increase - put
System.out.println(hashMap.put("angelababy1", "Great beauty"));//null
//Change - put. Since the key is unique and repeated at this time, the old value is overwritten - equivalent and modified. Return the overwritten old value. If there is no overwrite, return null
System.out.println(hashMap.put("angelababy1", "Medium beautiful"));//Great beauty
System.out.println(hashMap.put("angelababy2", "Little pretty"));//null
System.out.println(hashMap.put("angelababy3", "Great beauty"));//null

//Delete - remove, delete according to the key value and return the value of the deleted element
System.out.println(hashMap.remove("angelababy1"));//Medium beautiful
System.out.println(hashMap.remove("angelababy1", "Medium beautiful"));//false

//Query -- get the value of value according to the key value. If there is no kv binding, null will be returned
System.out.println(hashMap.get("angelababy1"));//null

//Get all the key sets in the map set
System.out.println(hashMap.keySet());//[angelababy3, angelababy2]

//Get all the k-v key value pairs in the map set
System.out.println(hashMap.entrySet());//[angelababy3 = big beautiful, angelababy2 = small beautiful]

tips:

When using the put method, if the specified key is not in the set, there is no value corresponding to the key, null is returned, and the specified key value is added to the set;

If the specified key exists in the set, the return value is the value corresponding to the key in the set (the value is the old value before replacement), and the value corresponding to the specified key is replaced with the specified new value// Mark baby is mean, like the new and hate the old

1.4 Map set (value finding by key) traverses key value finding

Key value finding method: obtain the value corresponding to the key through the key in the element

Analysis steps:

  1. Get all the keys in the Map. Since the keys are unique, a Set collection is returned to store all the keys. Method tip: keyset()
  2. Traverse the Set set of keys to get each key.
  3. According to the key, get the value corresponding to the key. Method tip: get(K key)

Code demonstration:

public class MapDemo01 {
    public static void main(String[] args) {
        //Create a Map collection object 
        HashMap<String, String> map = new HashMap<String,String>();
        //Add element to collection 
        map.put("Hu Ge", "Huo Jianhua");
        map.put("Guo Degang", "Yu Qian");
        map.put("Joker Xue", "Zhang Wei");

        //Get all the keys, get the key set, and traverse the Map set in the way of "key finding value"
        Set<String> keys = map.keySet();
        // Traverse the key set to get each key
        for (String key : keys) {
          	//Key is the key
            //Get corresponding value
            String value = map.get(key);
            System.out.println(key+"of CP Yes:"+value);
        }  
    }
}

1.5 Entry key value pair object

  • There are two kinds of objects stored in the Map, one is key and the other is value. There is a one-to-one correspondence in the Map. This pair of objects is also called an entry in the Map
  • Entry encapsulates the correspondence of key value pairs into objects, that is, key value pair objects, so that when we traverse the Map set, we can obtain the corresponding keys and corresponding values from each key value pair object.

Since Entry represents a pair of keys and values, it also provides methods to obtain corresponding keys and values:

  • public K getKey(): get the key in the Entry object.
  • public V getValue(): get the value in the Entry object.

Methods to obtain all Entry key value pair objects are also provided in the Map collection:

  • public Set<Map. Entry < K, V > > entryset(): the collection of key value pair objects, which obtains the collection of all key value pair objects in the map collection (set set).

1.6 Map set traversal key value pair method

Key value pair method: obtain the keys and values in the key value pair object through each key value pair object in the collection.

Operation steps and diagrams:

  1. Get all key value pair (Entry) objects in the Map collection and return them in the form of Set collection. Method tip: entrySet().

  2. Traverse the Set set containing key value pair (Entry) objects to get each key value pair (Entry) object.

  3. Get the key and value in the Entry object through the key value pair (Entry) object. Method prompt: getkey() getValue()

// Create a Map collection object 
HashMap<String, String> map = new HashMap<String,String>();
// Add element to collection 
map.put("Hu Ge", "Huo Jianhua");
map.put("Guo Degang", "Yu Qian");
map.put("Joker Xue", "Zhang Wei");

// Get all entry objects and entrysets, and traverse the Map set in the way of "key value pair"
Set<Entry<String,String>> entrySet = map.entrySet();

// Traverse to get each entry object
for (Entry<String, String> entry : entrySet) {
    // analysis 
    String key = entry.getKey();
    String value = entry.getValue();  
    System.out.println(key+"of CP yes:"+value);
}

Map double column Set cannot be traversed directly by iterator or foreach, but it can be used if it is indirectly converted to Set set Set, which is a single column Set

1.7 HashMap stores keys of custom types

  • The key requirements are unique, and the key de duplication method is the same as that of HashSet (that is, you can use HashMap to store the data of user-defined key value pairs, and press alt insert to rewrite hashCode and equals in subclasses)

Exercise: each student (name, age) has his own home address. Then, since there is a corresponding relationship, the student object and home address are stored in the map set. Student object as key and home address as value// Collections store objects, string objects

Note that students with the same name and age are considered the same student.

Write student class:

class Student {
    private String name;
    private int age;

    public Student() {//alt insert 
    }

    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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    //alt insert, which can use HashMap to store the data of user-defined key value pairs
    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

Write test class:

public class HashMapTest {
    public static void main(String[] args) {
        //1. Create a Hashmap collection object// Address value of Student object and binding
        Map<Student,String> map = new HashMap<Student,String>();//polymorphic
        
        //2. Add elements.
        map.put(new Student("lisi",28), "Shanghai");
        map.put(new Student("wangwu",22), "Beijing");
        map.put(new Student("zhaoliu",24), "Chengdu");
        map.put(new Student("zhouqi",25), "Guangzhou");
        map.put(new Student("wangwu",22), "Nanjing");
        
        //3. Take out the element. Key value finding method
        Set<Student> keySet = map.keySet();
        for(Student key: keySet){
            String value = map.get(key);
            System.out.println(key.toString()+"....."+value);
        }
    }
}
  • When storing custom objects in HashMap, if the custom object exists as a key, the hashCode and equals methods of the object must be rewritten to ensure the uniqueness of the object
  • If you want to ensure that the key s stored in the map are consistent with the order of retrieval, you can use Java util. LinkedHashMap collection to store

1.8 LinkedHashMap (orderly access)

  • HashMap subclass LinkedHashMap, which is a data storage structure combined with linked list and hash table, has orderly access and fast speed
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put("Deng Chao", "Sun Li");
map.put("Lau Andy", "Carol ");
map.put("Li Chen", "Fan Bingbing");
System.out.println(map);

result:

Deng Chao, Sun Li
 Li Chen, Fan Bingbing
 Liu Dehua, Zhu Liqian

1.9 Map set exercise

Requirements:

Counts the number of occurrences of each character in a string.

analysis:

  1. Get a string object
  2. Create a Map set. The key represents the character and the value represents the number of times.
  3. Traverse the string to get each character.
  4. Judge whether there is this key in the Map.
  5. If not, it appears for the first time, and the storage times is 1; If yes, it indicates that it has occurred. Obtain the corresponding value for + +, and store it again.
  6. Print the final result

code:

public class MapTest {
	public static void main(String[] args) {
        findChar("xxnioowo");//Character keys and secondary values have been bound together, x:2;
    }
    
    private static void findChar(String line) {
        //1: Create a collection to store characters and how many times they appear
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        
        //2: Traverse the string, get each character, and judge
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);//x
            
            //Determine whether the character is in the keyset
            if (!map.containsKey(c)) {//Indicates that this character has not appeared
                //That was the first time
                map.put(c, 1);//x:1;
            } else {
                //Get the number of times before first
                Integer count = map.get(c);//1
                //count++;
                //Save update again
                map.put(c, ++count);//x:2;
            }
        }
        
        System.out.println(map);
    }
}

//Class code:
//"xxnioowo";// Character keys and secondary values have been bound together, corresponding relationship, binding relationship, x:2;
String s = "xxnioowo";
HashMap<Character,Integer> hm = new HashMap();//Key is unique, set, empty x=2;

//For each character key, judge whether the key is in the set
char[] arr = s.toCharArray();//. var automatically generates variables and receives the results of the method
for (char c : arr) {//c for each character (key), arr.for traverses the character array
    if (!hm.containsKey(c)){//Does not contain this character
        hm.put(c, 1);//x=1;
    }else {
        hm.put(c, hm.get(c)+1);//x=1+1;
    }
}

System.out.println(hm);
//If not, save the key and value to the collection 1 time
//If the key already exists, this character is still saved, and the value (original value (original value through get())+1)

2. Supplementary knowledge points

2.1 JDK9 quickly optimizes the data added to the collection

Usually, we create a Set (for example, List or Set) in our code and fill it directly with some elements. Instantiate the collection and call several add methods to duplicate the code.

List<String> list = new ArrayList<>();//Polymorphic list add("abc"); list. add("def"); list. add("ghi"); System. out. println(list);// []

Java 9 adds several collection methods to make it easier to create collections and map instances of a small number of elements.

The new static of methods of List, Set and Map can more easily create immutable instances of the Set (after adding the data Set, it cannot be changed, that is, elements cannot be added, deleted or modified, and the element traversal elements can be obtained. For example, the add and put methods can no longer be called to add data)

example:

Set<String> str1=Set.of("a","b","c");  //. var,str1 object name / / STR1 add("c"); There will be no error when compiling here, but an error will be reported when executing. Because it is an immutable set, you can't add the element system out. println(str1);   Map<String,Integer> str2=Map. of("a",1,"b",2);// A is the key and 1 is the value system out. println(str2); List<String> str3=List. of("a","b");   System. out. println(str3);  

Attention should be paid to the following two points:

1: The of () method is only a static method of the three interfaces of Map, List and Set. Its parent interface and subclass implementation do not have such methods, such as HashSet, ArrayList, etc;

2: The returned set is immutable; Born fixed dead, you can't add, delete or change elements, but you can get elements through traversal

2.2 Debug tracking

Use the breakpoint debugging function of IDEA to view the running process of the program and the change process of variables

3. Simulated landlords shuffle, deal and watch cards

3.1 case introduction

Complete the shuffle and deal according to the rules of landlords. The specific rules are as follows:

  1. Assemble 54 playing cards
  2. 54 cards out of order
  3. Three players participate in the game, three people touch cards alternately, 17 cards per person, and the last three cards are reserved for the bottom card.
  4. Check the cards in their hands (sorted according to the size of the cards) and their cards

Rules: put the playing cards in the order from big to small: King, Wang, 2,A,K,Q,J,10,9,8,7,6,5,4,3

3.2 case demand analysis

  1. Prepare cards: complete the mapping relationship between numbers and cards: use the double column Map(HashMap) set to complete the corresponding relationship between a number and string cards (equivalent to a dictionary)

  2. Shuffle: complete the shuffle and deal through numbers

  3. Licensing: Design everyone and the bottom card as ArrayList, store the last three cards directly in the bottom card, and deal the remaining cards in turn by taking a mold of three.

In the process of storage, the number size is required to correspond to the size of the landlord rule. Assign numbers representing different cards to different players and cards.

  1. Card reading: find the corresponding character display through the Map set. By querying the corresponding relationship between cards and numbers, the numbers are converted into card strings for display.

3.3 implementation code steps (be able to use HashMap to write the case of landlords shuffling and licensing)

public class Poker {
     public static void main(String[] args) {
        //Key and value binding, numbering idea, bind a number for each card, 0 number corresponds to the largest card, 1, secondary big card, the corresponding relationship is worked out, and the numbering key binds the card value
        HashMap<Integer,String> hm  = new HashMap<>();//empty

        //King and Xiao Wang are the largest and simplest, with binding number
        int count = 0;//Start number
        hm.put(count++,"king");//0
        hm.put(count++,"Xiao Wang");//1
        //2,♠2,3,♥2

        //Make cards, ♠ 2. Single row collection of designs and colors and single row collection of numbers are spliced into cards
        ArrayList<String> color = new ArrayList<>();//
        ArrayList<String> num = new ArrayList<>();

        Collections.addAll(color, "♠", "♥", "♣", "♦");
        Collections.addAll(num, "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");
        //Splice, get the numbers, traverse the designs and colors, orderly, from large to small, unclear, and print them separately
        for (String n : num) {
            //n:2", "A", "K", "Q", "J",
            for (String c : color) {
                hm.put(count++,c+n);//1
            }
        }

        System.out.println(hm);//Find the value through the key and bind it

        //Shuffle, shuffle the number, because the number key binds the card value. Through the number, you can find the card, collection tool class, random replacement, list set required, key set and number set
        Set<Integer> keyset = hm.keySet();//Number set, ordered set, random replacement method
        ArrayList<Integer> numberList = new ArrayList<Integer>();
        numberList.addAll(keyset);//numberList number collection is here
        Collections.shuffle(numberList);//It's messed up. All the numbers

        //Deal cards and issue numbers according to certain conditions, because the number key binds the card value, and the card can be found through the number
        //Number set, everyone has one, three players, cards
        ArrayList<Integer> one = new ArrayList<>();//Part number
        ArrayList<Integer> two = new ArrayList<>();
        ArrayList<Integer> three = new ArrayList<>();
        ArrayList<Integer> last = new ArrayList<>();

        for (int i = 0; i < numberList.size(); i++) {
            Integer pernum = numberList.get(i);//The total number set, and each number is allocated according to the index of the number set

            if (i>=51){
                last.add(pernum);//Everyone gets their own number set, but the numbers in it are not well sorted and disordered
            }else {
                if (i%3==0){
                    one.add(pernum);
                }else if (i%3==1){
                    two.add(pernum);
                }else {
                    three.add(pernum);
                }
            }

        }

        //In each person's number set, the number is in order, and the cards are in order, because the number key binds the card value and tool class
        Collections.sort(one);//0,1..
        Collections.sort(two);
        Collections.sort(three);
        Collections.sort(last);

        //The numbers are arranged in order, and the number key binds the card value. For each number, find each card and store it in various card sets, player card sets Card set storage card
        ArrayList<String> player1 = new ArrayList<String>();//Player 1 card collection, empty, find the card by number
        ArrayList<String> player2 = new ArrayList<String>();
        ArrayList<String> player3 = new ArrayList<String>();
        ArrayList<String> dipai = new ArrayList<String>();


        for (Integer o : one) {
            String p = hm.get(o);//For each number, find each card, number, order, arrange and bind
            player1.add(p);
        }

        for (Integer o : two) {
            String p = hm.get(o);//Every number, every card,
            player2.add(p);
        }

        for (Integer o : three) {
            String p = hm.get(o);//Every number, every card,
            player3.add(p);
        }

        for (Integer o : last) {
            String p = hm.get(o);//Every number, every card,
            dipai.add(p);
        }

        //Look at the cards and print the set
        System.out.println("linghu chong:"+player1);
        System.out.println("Stone breaks the sky:"+player2);
        System.out.println("Jiu Mozhi:"+player3);
        System.out.println("a hand:"+dipai);
    }
}

Keywords: Java data structure

Added by sloth456 on Mon, 31 Jan 2022 03:39:49 +0200