java advanced Map collection

Posted by TheIceman5 on Wed, 22 Dec 2021 03:11:53 +0100

1 map < K, V > Collection: different from the Collection interface, a pair of elements are stored each time, that is

The relationship between K (key) and V (value) is called mapping.

Mapping rules: keys are unique and values can be repeated, but a key can only correspond to one value.

Common implementation classes of 2Map interface:

1hashmap < K, V > Set: the bottom layer is hash table, which is fast, disordered, multi-threaded, unsafe and can store null

1.1 LinkedHashMap < k.v >: the bottom layer is hash table + linked list to ensure the order of iterative elements

2 hashtable < K, V >: it is a thread safe collection. It is single threaded and slow. It cannot store null values and null keys

2.1 Properties: unique collection combined with io stream

Common methods in 3Map interface:

1public v put (K key, V value): adds the specified key and value to the Map collection

Note: if the key has only one return value, V is null. If the key is repeated, the old value will be replaced with the new value

value and return.

2 public V remove (Object key): deletes the key value pair corresponding to the specified key from the Map collection

3 public V get (Object key): returns the corresponding value value if the key exists

4 boolean containsKey (Object Key): judge whether the set contains the specified key

        5 List<E> of (a,,b,c,d......): Add multiple elements to the collection at one time (both list and set map can be used).

Usage premise: the number of storage elements in the collection has been determined and will not be changed

Precautions for use: 1 this method is only applicable to the List Set Map interface, not the implementation class of the interface

2. The return value of the of method is also a set that cannot be changed, and no more elements can be added

3. Set and Map interfaces cannot have duplicate elements when using the of method

Traversal of 4Map set:

The first method is keySet: first, put all the keys in the Map Set into a Set through the keySet () method,

Then traverse the Set set, and finally pass the map The get method also finds the corresponding value.

               

The second method: set < map Entry < k, V > >: entry is the proof of the combination of k and value. Called "key value pair object"

                              Set<Map. Entry < K, V > > store the entry proof in a set set, and then traverse the set

Close. Then enter through the two methods in the entry object GetKey () and entry getValue

Get key and value

                          

5HashMap stores the key values of user-defined types: because the keys in the Map cannot be repeated, pay attention to using the user-defined class as the key value

When it occurs, override the hashCode and equals methods

Case 1: calculate the number of each character in the input string

package com.bed.javahighclass;

import java.util.HashMap;
import java.util.Scanner;

public class CharacterCount {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Please enter");
        String str=sc.next();

        char[] strings=str.toCharArray();//Converts the input string to a character group
        HashMap<Character,Integer> map=new HashMap();//Create a HashMap collection to receive the results

        for (char c : strings) {
            if (map.containsKey(c)){
                //If the character c already exists in the map set, let the value corresponding to C + 1
                Integer value=map.get(c);
                value++;
                map.put(c,value);
            }else{//If this character appears for the first time
                map.put(c,1);
            }
            }
        System.out.println(map);
        }
    }

6 program debug: let the program execute line by line and check the running results of each line. Just know the function of each button.

Case: orderly arrangement of landlords' licensing

package com.bed.javahighclass;

import java.sql.ClientInfoStatus;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class DouDiZhuIndex {

    public static void main(String[] args) {
        HashMap<Integer, String> poker = new HashMap<>();//The main collection used to store cards. The front is the index and the back is the decor
        ArrayList<Integer> pokerindex = new ArrayList<>();//Take out a separate set of indexes

        List<String> huase = List.of("♥", "♠", "♦", "♣");
        List<String> numbers = List.of("2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");
        //Add king and Xiao Wang and the corresponding index value to the total set and index
        int index = 0;
        poker.put(index, "king");//The default index is 0
        pokerindex.add(index);
        index++;
        poker.put(index, "Xiao Wang");//Xiao Wang is 1
        pokerindex.add(index);
        //Assemble the cards and put them into the total poker set and index set. Here, the assembly is carried out in the order of 16 lines
        for (String number : numbers) {
            for (String s : huase) {
                index++;
                pokerindex.add(index);
                poker.put(index, s + number);//♥ 2index is 3 
            }
        }
        System.out.println(pokerindex);
        System.out.println(poker);
        System.out.println("===========================");

        Collections.shuffle(pokerindex);//shuffle the cards

        //Licensing, to be exact, is the index of licensing to each player
        ArrayList<Integer> player01 = new ArrayList<>();
        ArrayList<Integer> player02 = new ArrayList<>();
        ArrayList<Integer> player03 = new ArrayList<>();
        ArrayList<Integer> dipai = new ArrayList<>();
        for (int i = 0; i <pokerindex.size(); i++) {
            if (i >= 51) {
                dipai.add(pokerindex.get(i));
            } else if (i % 3 == 0) {
                player01.add(pokerindex.get(i));
            } else if (i % 3 == 1) {
                player02.add(pokerindex.get(i));
            } else if (i % 3 == 2) {
                player03.add(pokerindex.get(i));
            }
        }
        //Sort the cards in the player's hand
        Collections.sort(player01);
        Collections.sort(player02);
        Collections.sort(player03);
        Collections.sort(dipai);


        //Call the pokershow method
        pokershow(poker,player01);
        pokershow(poker,player02);
        pokershow(poker,player03);
        pokershow(poker,dipai);
    }
    //Define a method to transfer the total set of cards and player index, deal cards to each player and display them
    public static void pokershow(HashMap<Integer, String> poker,ArrayList<Integer> List){
        for (Integer key : List) {
            String s = poker.get(key);//Key value corresponding to index value
            System.out.print(s+" ");
        }
        System.out.println("");
        }

    }