JavaSE foundation-(18) Map collection

table of Contents

1. Map collection

1.1 Overview of Map Collection

1.2 The difference between Map collection and Collection collection

1.3 Overview of Map function

Second, the traversal of the Map collection

2.1 Iterating according to the key set 

2.2 Iterating objects based on key values

2.3 Enhanced for loop traversal

Three, the key is a custom object

Four, LinkedHashMap collection

Five, TreeMap collection

Six, count the number of occurrences of each character in the string

Seven, the difference between HashMap and Hashtable

8. Simulate Doudizhu shuffle and deal practice

Nine, generic fixed upper and lower boundaries (to be added)

9.1 Generic fixed upper boundary

9.2 Generic fixed lower boundary


 

1. Map collection

1.1 Overview of Map Collection

Map in java is used to store data with mapping relationship, and two sets of values ​​are stored in the Map collection.

One group is used to store the key of the Map, and the other group is used to store the value of the Map. Map is an interface that maps key values ​​to values.

A mapping cannot contain duplicate key values, and each key is mapped to at most one value.

 

1.2 The difference between Map collection and Collection collection

  • Map stores two sets of values, and Collection is a set of values
  • The Map key is unique, and the Set key of the Collection subinterface is unique
  • The data structure value of the Map collection is valid for the key and has nothing to do with the value; the data structure of the Collection collection is valid for the element

 

1.3 Overview of Map function

  • Add function
    • V put(K key,V value)//Add element
      • If the key is stored for the first time, store the element directly and return null
      • If the key already exists, replace the previous old value with the value and return the previous value
  • Delete function
    • void clear()//Delete all key-value pair elements
    • V remove(Object key)//Remove key-value pair elements according to the key and return the value
  • Judgment function
    • boolean containsKey(Object key)//Determine whether the collection contains the specified key
    • boolean containsValue(Object value)//Determine whether the collection contains the specified value
    • boolean isEmpty()//Determine whether the collection is empty
  • Get function
    • Set<Map.Entry<K,V>> entrySet()
    • V get(Object key)//Get the value according to the key
    • Set<K> ketSet()//Get the set of all keys in the set
    • Collection<V> values()//Get the collection of all values ​​in the collection
  • Length function
    • int size()//Returns the number of key-value pairs in the collection

 

Second, the traversal of the Map collection

2.1 Iterating according to the key set 

Since there is no iterator method in Map, when we traverse the Map collection,

First, it will get the set of keys keySet, and then traverse all the keys through the iterator of keySet,

Finally, the corresponding value is obtained through the key to achieve the traversal effect on the Map collection. The following is a program demonstration,

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapTest {
    public static void main(String[] args) {
        Map<String,Integer> map=new HashMap<>();
        map.put("测试1",21);
        map.put("测试2",22);
        map.put("测试3",23);

        Set<String> ketSet=map.keySet();
        Iterator<String> it=ketSet.iterator();
        while(it.hasNext()){
            String key=it.next();
            Integer i=map.get(key);
            System.out.println(key+"="+i);
        }
    }
}

 

2.2 Iterating objects based on key values

We turn the key-value pair of the two-column set into the key-value pair object of the single-column set,

Then iterate over this collection, get each key-value pair object, and get the size of the key and value according to the key-value pair object.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapTest {
    public static void main(String[] args) {
        Map<String,Integer> map=new HashMap<>();
        map.put("测试1",21);
        map.put("测试2",22);
        map.put("测试3",23);

        //Map.Entry说明Entry是Map的内部接口,将键和值封装成了Entry对象并存储在Set集合中
        Set<Map.Entry<String,Integer>> entrySet=map.entrySet();
        Iterator<Map.Entry<String,Integer>> it=entrySet.iterator();
        while(it.hasNext()){
            Map.Entry<String,Integer> entry=it.next();
            System.out.println(entry.getKey()+"="+entry.getValue());
        }
    }
}

 

2.3 Enhanced for loop traversal

We can also use the enhanced for loop to traverse the Map collection, this way will be simpler,

import java.util.HashMap;
import java.util.Map;

public class MapTest {
    public static void main(String[] args) {
        Map<String,Integer> map=new HashMap<>();
        map.put("测试1",21);
        map.put("测试2",22);
        map.put("测试3",23);

        for(String key:map.keySet()){
            System.out.println(key+"="+map.get(key));
        }
    }
}

 

Three, the key is a custom object

If we use a custom object as a key and store it in the HashMap, if the collection has to ensure the uniqueness of the key,

You must rewrite the equals method and hashCode method in the custom object,

Let's test it, the key is a custom object of Student, the value is a string of native place,

import java.util.HashMap;

public class MapTest {
    public static void main(String[] args) {
        HashMap<Student,String> hashMap=new HashMap<>();
        hashMap.put(new Student("测试1",21),"武汉");
        hashMap.put(new Student("测试1",21),"长沙");
        hashMap.put(new Student("测试1",21),"郑州");
        hashMap.put(new Student("测试1",21),"南昌");

        System.out.println(hashMap);
    }
}

It can be seen that only the last value of the previous Student object with the same attribute is stored, and the same key will continue to overwrite the previous value.

 

Four, LinkedHashMap collection

LinkedHashMap is a HashMap implemented using a linked list. Its characteristic is that the access sequence is consistent. Let's test it briefly:

    public static void main(String[] args) {
        LinkedHashMap<String,Integer> linkedHashMap=new LinkedHashMap<>();
        linkedHashMap.put("测试1",21);
        linkedHashMap.put("测试3",23);
        linkedHashMap.put("测试2",22);

        System.out.println(linkedHashMap);
    }

 

Five, TreeMap collection

TreeMap is similar to TreeSet in that it is also an ordered collection, which stores key-value pairs and is a two-column collection.

In the same way, if the key is a custom object, you must inherit Comparable from the custom object and implement the compareTo method.

    public static void main(String[] args) {
        TreeMap<Student,String> treeMap=new TreeMap<>();
        treeMap.put(new Student("测试1",23),"武汉");
        treeMap.put(new Student("测试2",22),"长沙");
        treeMap.put(new Student("测试3",21),"郑州");

        System.out.println(treeMap);
    }

At the same time, we can also pass a comparator method to specify the sorting rules when the TreeMap is constructed.

Let’s change the sorting rule, sort by name, test it to see the effect,

    public static void main(String[] args) {
        TreeMap<Student,String> treeMap=new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num=o1.getName().compareTo(o2.getName());
                return num==0?o1.getAge()-o2.getAge():num;
            }
        });
        treeMap.put(new Student("测试1",23),"武汉");
        treeMap.put(new Student("测试2",22),"长沙");
        treeMap.put(new Student("测试3",21),"郑州");

        System.out.println(treeMap);
    }

 

Six, count the number of occurrences of each character in the string

A string is required, and the number of occurrences of each character in it needs to be counted.

public class MapTest {
    public static void main(String[] args) {
        String str="aaabbbbbccd";
        char arr[]=str.toCharArray();

        HashMap<Character,Integer> hashMap=new HashMap<>();
        for(char c:arr){
            if(!hashMap.containsKey(c)){
                hashMap.put(c,1);
            }else{
                hashMap.put(c,hashMap.get(c)+1);
            }
        }

        System.out.println(hashMap);
    }
}

 

Seven, the difference between HashMap and Hashtable

The bottom layers of HashMap and Hashtable are supported by hash algorithms, both are two-column sets, and they store keys and values.

But they mainly have the following differences,

  • Hashtable is thread-safe and inefficient. Hashtable cannot store null keys and null values
  • HashMap is thread-unsafe and efficient. HashMap can store null keys and null values

 

8. Simulate Doudizhu shuffle and deal practice

import java.util.ArrayList;
import java.util.Collections;

public class MapTest {
    public static void main(String[] args) {
        String num[]={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        String color[]={"方片","梅花","黑桃","红桃"};
        ArrayList<String> poker=new ArrayList<>();

        //添加扑克牌到牌库
        for(String pokerColor:color){
            for(String pokerNum:num){
                poker.add(pokerColor.concat(pokerNum));//concat链接俩字符串
            }
        }
        poker.add("小王");
        poker.add("大王");

        //洗牌
        Collections.shuffle(poker);//随机打乱原来的顺序

        //发牌
        ArrayList<String> player1=new ArrayList<>();
        ArrayList<String> player2=new ArrayList<>();
        ArrayList<String> player3=new ArrayList<>();
        ArrayList<String> cardsOfLandlord=new ArrayList<>();

        for (int i = 0; i <poker.size() ; i++) {
            if(i>=poker.size()-3){
                cardsOfLandlord.add(poker.get(i));
            }else if(i%3==0){
                player1.add(poker.get(i));
            }else if(i%3==1){
                player2.add(poker.get(i));
            }else if(i%3==2){
                player3.add(poker.get(i));
            }
        }

        //看牌
        System.out.println("玩家一手牌:"+player1);
        System.out.println("玩家二手牌:"+player2);
        System.out.println("玩家三手牌:"+player3);
        System.out.println("地主奖励底牌:"+cardsOfLandlord);
    }
}

We can find that there is no order in the hand at this time. Now we use HashMap to construct key-value pairs,

The 54 playing cards correspond to 54 numbers (note that the size relationship corresponding to the 54 numbers here is the size relationship we want to sort the playing cards, for example, club 3 corresponds to 0, club 4 corresponds to 4, and club 5 corresponds to 8. analogy),

Then 54 numbers are stored directly in the ArrayList, randomly scrambled,

Then use TreeSet to store these 54 numbers, and store them according to the sorting relationship we want when storing.

At the end of the display, you can see that the hand is in order. Let’s try the effect.

import java.util.*;

public class MapTest {
    public static void main(String[] args) {
        String num[]={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
        String color[]={"♦","♣","♠","♥"};
        HashMap<Integer,String> pokerHash=new HashMap<>();
        ArrayList<Integer> pokerList=new ArrayList<>();

        //构造好扑克牌的HashMap
        for(int i=0;i<num.length;i++){
            for(int j=0;j<color.length;j++){
                pokerHash.put(i*4+j,color[j].concat(num[i]));//concat链接俩字符串
            }
        }
        pokerHash.put(52,"小王");
        pokerHash.put(53,"大王");

        //添加对应数字到数组中
        for (int i = 0; i < 54; i++) {
            pokerList.add(i);
        }

        //洗牌
        Collections.shuffle(pokerList);//随机打乱原来的顺序

        //发牌
        TreeSet<Integer> player1=new TreeSet<>();
        TreeSet<Integer> player2=new TreeSet<>();
        TreeSet<Integer> player3=new TreeSet<>();
        TreeSet<Integer> cardsOfLandlord=new TreeSet<>();

        for (int i = 0; i <pokerList.size() ; i++) {
            if(i>=pokerList.size()-3){
                cardsOfLandlord.add(pokerList.get(i));
            }else if(i%3==0){
                player1.add(pokerList.get(i));
            }else if(i%3==1){
                player2.add(pokerList.get(i));
            }else if(i%3==2){
                player3.add(pokerList.get(i));
            }
        }

        //看牌
        System.out.print("玩家1手牌:");
        Iterator<Integer> it1=player1.iterator();
        while(it1.hasNext()){
            Integer it=it1.next();
            System.out.print(pokerHash.get(it)+" ");
        }
        System.out.println();

        System.out.print("玩家2手牌:");
        Iterator<Integer> it2=player2.iterator();
        while(it2.hasNext()){
            Integer it=it2.next();
            System.out.print(pokerHash.get(it)+" ");
        }
        System.out.println();

        System.out.print("玩家3手牌:");
        Iterator<Integer> it3=player3.iterator();
        while(it3.hasNext()){
            Integer it=it3.next();
            System.out.print(pokerHash.get(it)+" ");
        }
        System.out.println();

        System.out.print("地主奖励底牌:");
        Iterator<Integer> it4=cardsOfLandlord.iterator();
        while(it4.hasNext()){
            Integer it=it4.next();
            System.out.print(pokerHash.get(it)+" ");
        }
    }
}

 

Nine, generic fixed upper and lower boundaries (to be added)

9.1 Generic fixed upper boundary

? extends E

The popular understanding is that as long as it is a subclass of E or similar objects, the parent class object can be pointed to by the subclass reference.

 

9.2 Generic fixed lower boundary

? super E

Popular understanding is that some functions are implemented in E, and subclasses of E can also be used.

 

Guess you like

Origin blog.csdn.net/weixin_39478524/article/details/112779447