JAVA Foundation-Chapter Fourteen Map

main content

Map集合

teaching objectives

能够说出Map集合特点
使用Map集合添加方法保存数据
使用”键找值”的方式遍历Map集合
使用”键值对”的方式遍历Map集合
能够使用HashMap存储自定义键值对的数据
能够使用HashMap编写斗地主洗牌发牌案例

Chapter 1 Map Collection

1. 1 Overview

In real life, we often see such a collection: IP address and host name, ID number and individual, system user name and system user object, etc.

This one-to-one correspondence is called mapping. Java provides a special collection class to store the objects of this kind of object relationship, namely the java.util.Map
interface.

By checking the description of the Map interface, we found that the collection under the Map interface and the collection under the Collection interface have different forms of data storage, as
shown in the figure below.

Collection中的集合,元素是孤立存在的(理解为单身),向集合中存储元素采用一个个元素的方式存储。
Map中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键可以找对所对应的
值。
Collection中的集合称为单列集合,Map中的集合称为双列集合。
需要注意的是,Map中的集合不能包含重复的键,值可以重复;每个键只能对应一个值。

1. 2 Map commonly used subclasses

By looking at the Map interface description, we can see that Map has multiple subclasses. Here we mainly explain the commonly used HashMap collection and LinkedHashMap collection.

HashMap:存储数据采用的哈希表结构,元素的存取顺序不能保证一致。由于要保证键的唯一、不重复,需
要重写键的hashCode()方法、equals()方法。
LinkedHashMap:HashMap下有个子类LinkedHashMap,存储数据采用的哈希表结构+链表结构。通过链
表结构可以保证元素的存取顺序一致;通过哈希表结构可以保证的键的唯一、不重复,需要重写键的
hashCode()方法、equals()方法。
tips:Map接口中的集合都有两个泛型变量,在使用时,要为两个泛型变量赋予数据类型。两个泛型变量的数
据类型可以相同,也可以不同。

1. 3 Common methods in the Map interface

Many methods are defined in the Map interface, the commonly used ones are as follows:

public V put(K key, V value): 把指定的键与指定的值添加到Map集合中。
public V remove(Object key): 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的
值。
public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
public Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。
public Set<Map.Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。

Method demonstration of the Map interface

tips:
使用put方法时,若指定的键(key)在集合中没有,则没有这个键对应的值,返回null,并把指定的键值添加到
集合中;
若指定的键(key)在集合中存在,则返回值为集合中键对应的值(该值为替换前的值),并把指定键所对应的
值,替换成指定的新值。

1. 4 Map collection traversal key finding method

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

Analysis steps:

1. 获取Map中所有的键,由于键是唯一的,所以返回一个Set集合存储所有的键。方法提示:keyset()
2. 遍历键的Set集合,得到每一个键。
3. 根据键,获取键所对应的值。方法提示:get(K key)

Code demo:

public class MapDemo {
public static void main(String[] args) {
//创建 map对象
HashMap<String, String> map = new HashMap<String, String>();
//添加元素到集合
map.put("黄晓明", "杨颖");
map.put("文章", "马伊琍");
map.put("邓超", "孙俪");
System.out.println(map);
//String remove(String key)
System.out.println(map.remove("邓超"));
System.out.println(map);
// 想要查看 黄晓明的媳妇 是谁
System.out.println(map.get("黄晓明"));
System.out.println(map.get("邓超"));
}
}
public class MapDemo 01  {
public static void main(String[] args) {
//创建Map集合对象
HashMap<String, String> map = new HashMap<String,String>();
//添加元素到集合
map.put("胡歌", "霍建华");
map.put("郭德纲", "于谦");
map.put("薛之谦", "大张伟");

//Get all the keys to get the key set

Traverse the diagram:

1. 5 Entry key-value pair object

We already know, the Map is stored in two kinds of objects, called a key (key), called value (value), which are one-off in the Map of
the Department, also known as the object to do An Entry in the Map. Entry encapsulates the correspondence of key-value pairs into objects. That is, the key-value pair object, so
when we traverse the Map collection, we can get the corresponding key and corresponding value from each key-value pair (Entry) object.

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

public K getKey():获取Entry对象中的键。
public V getValue():获取Entry对象中的值。

The Map collection also provides methods to obtain all Entry objects:

public Set<Map.Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。

1. 6 Map collection traversal key-value pair method

Key-value pair method: Get the key and value in the key-value pair (Entry) object through each key-value pair (Entry) object in the collection.

Operation steps and diagrams:

1. 获取Map集合中,所有的键值对(Entry)对象,以Set集合形式返回。方法提示:entrySet()。
2. 遍历包含键值对(Entry)对象的Set集合,得到每一个键值对(Entry)对象。
Set<String> keys = map.keySet();
// 遍历键集 得到 每一个键
for (String key : keys) {
//key 就是键
//获取对应值
String value = map.get(key);
System.out.println(key+"的CP是:"+value);
}
}
}
3. 通过键值对(Entry)对象,获取Entry对象中的键与值。 方法提示:getkey() getValue()

Traverse the diagram:

tips:Map集合不能直接使用迭代器或者foreach进行遍历。但是转成Set之后就可以使用了。

1.7 HashMap stores custom type keys

Exercise: Every student (name, age) has his own home address. Then, since there is a corresponding relationship, store the student object and home address in

map collection. Student as the key and home address as the value.

注意,学生姓名相同并且年龄相同视为同一名学生。

Write student class:

public class MapDemo 02  {
public static void main(String[] args) {
// 创建Map集合对象
HashMap<String, String> map = new HashMap<String,String>();
// 添加元素到集合
map.put("胡歌", "霍建华");
map.put("郭德纲", "于谦");
map.put("薛之谦", "大张伟");
// 获取 所有的 entry对象 entrySet
Set<Entry<String,String>> entrySet = map.entrySet();
// 遍历得到每一个entry对象
for (Entry<String, String> entry : entrySet) {
// 解析
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"的CP是:"+value);
}
}
}
public class Student {

Write the test class:

private String name;
private int age;
public Student() {
}
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 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);
}
}
public class HashMapTest {
public static void main(String[] args) {
// 1 ,创建Hashmap集合对象。
Map<Student,String>map = new HashMap<Student,String>();
// 2 ,添加元素。
map.put(newStudent("lisi", 28 ), "上海");
map.put(newStudent("wangwu", 22 ), "北京");
map.put(newStudent("zhaoliu", 24 ), "成都");
当给HashMap中存放自定义对象时,如果自定义对象作为key存在,这时要保证对象唯一,必须复写对象的
hashCode和equals方法(如果忘记,请回顾HashSet存放自定义对象)。
如果要保证map中存放的key和取出的顺序一致,可以使用java.util.LinkedHashMap集合来存放。

1. 8 LinkedHashMap

We know that HashMap guarantees that the paired elements are unique, and the query speed is fast, but the paired elements are stored in no order, so what should we do if we want to ensure
order and speed?

There is a subclass LinkedHashMap under HashMap, which is a data storage structure that combines a linked list and a hash table.

result:

1.9 Map collection exercise

demand:

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

analysis:

1. Get a string object

2. 创建一个Map集合,键代表字符,值代表次数。
map.put(newStudent("zhouqi", 25 ), "广州");
map.put(newStudent("wangwu", 22 ), "南京");
// 3 ,取出元素。键找值方式
Set<Student>keySet = map.keySet();
for(Student key: keySet){
Stringvalue = map.get(key);
System.out.println(key.toString()+"....."+value);
}
}
}
public class LinkedHashMapDemo {
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put("邓超", "孙俪");
map.put("李晨", "范冰冰");
map.put("刘德华", "朱丽倩");
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}

Deng Chao and Sun Li

Li Chen Fan Bingbing

Andy Lau Zhu Liqian

3. Traverse the string to get each character.

4. 判断Map中是否有该键。
5. 如果没有,第一次出现,存储次数为 1 ;如果有,则说明已经出现过,获取到对应的值进行++,再次存储。
6. 打印最终结果

Code:

Chapter 2 Supplementary Knowledge Points

2. 1 JDK 9 adds optimizations to collections

Usually, we create a collection (for example, List or Set) in the code and fill it directly with some elements. To instantiate the collection, several add methods are
called, making the code repetitive.

public class MapTest {
public static void main(String[] args) {
//友情提示
System.out.println("请录入一个字符串:");
String line = new Scanner(System.in).nextLine();
// 定义 每个字符出现次数的方法
findChar(line);
}
private static void findChar(String line) {
// 1 :创建一个集合 存储 字符 以及其出现的次数
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
// 2 :遍历字符串
for (int i =  0 ; i < line.length(); i++) {
char c = line.charAt(i);
//判断 该字符 是否在键集中
if (!map.containsKey(c)) {//说明这个字符没有出现过
//那就是第一次
map.put(c,  1 );
} else {
//先获取之前的次数
Integer count = map.get(c);
//count++;
//再次存入 更新
map.put(c, ++count);
}
}
System.out.println(map);
}
}

In Java 9, several collection factory methods have been added to make it easier to create collections and map instances of a small number of elements. The new static factory methods for List, Set, and Map
make it easier to create immutable instances of collections.

example:

Need to pay attention to the following two points:

1 :of()方法只是Map,List,Set这三个接口的静态方法,其父类接口和子类实现并没有这类方法,比如
HashSet,ArrayList等待;
2 :返回的集合是不可变的;

2. 2 Debug tracking

Use IDEA's breakpoint debugging function to view the running process of the program

1. In the valid code line, click on the blank area to the right of the line number to set a breakpoint. The program will stop when it is executed. We can run the program manually

public class Demo 01  {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("abc");
list.add("def");
list.add("ghi");
System.out.println(list);
}
}
public class HelloJDK 9  {
public static void main(String[] args) {
Set<String> str 1 =Set.of("a","b","c");
//str 1 .add("c");这里编译的时候不会错,但是执行的时候会报错,因为是不可变的集合
System.out.println(str 1 );
Map<String,Integer> str 2 =Map.of("a", 1 ,"b", 2 );
System.out.println(str 2 );
List<String> str 3 =List.of("a","b");
System.out.println(str 3 );
}
}
  1. Click Debug run mode

  2. The program stops at the breakpoint and no longer executes, and the Debug window is opened at the bottom of IDEA

  3. Introduction to Debug window

5. Shortcut key F 8, the code executes one line down, the ninth line is executed, and the execution reaches the 10th line (the 10th line has not been executed yet)

6. Switch to the console panel, please enter a character string when the console displays: and wait for the keyboard to enter

  1. Shortcut key F 8, the program continues to execute backwards, performs keyboard entry operations, and enters data ababcea in the console

Effect after carriage return:

Debug interface effect:

  1. At this point, reach the findChar method, the shortcut key F7, enter the method findChar
9. 快捷键F 8 接续执行,创建了map对象,变量区域显示
  1. The shortcut key F 8 continues execution and enters the loop, the loop variable i is 0, and F 8 continues to execute, and the variable c is assigned the character'a' byte value 97

  2. The shortcut key F 8 continues execution and enters the judgment sentence, because the character is not in the Map set key set, press F 8 again to execute and enter the judgment

  3. Shortcut key F 8 continues execution, the cycle ends, and enters the next cycle, at this time a pair of elements have been added to the map

13. The shortcut key F 8 continues execution, enters the next cycle, and then continues the above operation, we can see how the code is executed each time

  1. If you don’t want to continue debugging, you can use the shortcut key F9, the program executes normally to the end, and the program result is displayed on the console

Chapter 3 Simulated Landlord Shuffle and Deal

3. 1 Case introduction

According to the rules of Doudizhu, complete the action of shuffling the cards.

Specific rules:

1. Assemble 54 playing cards

2. The order of 54 cards is shuffled

3. Three players participate in the game, and the three draw cards alternately, each with 17 cards, and the last three are reserved as hole cards.

4. Check the cards in the hands of the three (in order of card size) and hole cards

Rules: The order of playing cards in hand from big to small: King, King, 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 two-column Map (HashMap) collection to complete the correspondence between a number and a string card (equivalent to a dictionary).

2. 洗牌:

Reshuffle the cards by numbers

3. 发牌:

Design everyone and the hole cards as an ArrayList, store the last 3 cards directly in the hole cards, and the remaining cards will be dealt in sequence by taking the mold of the 3.

In the process of storage, the size of the number is required to correspond to the size of the rules of the landlord.

Assign numbers representing different cards to different players and hole cards.

4. 看牌:

Find the corresponding character display through the Map collection.

By querying the correspondence between cards and numbers, the numbers are converted into strings of cards and then displayed.

3. 3 implementation code steps

public class Poker {
public static void main(String[] args) {
/*
*  1 组装 54 张扑克牌
*/
//  1. 1  创建Map集合存储
HashMap<Integer, String> pokerMap = new HashMap<Integer, String>();
//  1. 2  创建 花色集合 与 数字集合
ArrayList<String> colors = new ArrayList<String>();
ArrayList<String> numbers = new ArrayList<String>();
//  1. 3  存储 花色 与数字
Collections.addAll(colors, "♦", "♣", "♥", "♠");
Collections.addAll(numbers, " 2 ", "A", "K", "Q", "J", " 10 ", " 9 ", " 8 ", " 7 ", " 6 ", " 5 ", " 4 ",
" 3 ");
// 设置 存储编号变量
int count =  1 ;
pokerMap.put(count++, "大王");
pokerMap.put(count++, "小王");
//  1. 4  创建牌 存储到map集合中
for (String number : numbers) {
for (String color : colors) {
String card = color + number;
pokerMap.put(count++, card);
}
}
/*
*  2  将 54 张牌顺序打乱
*/
// 取出编号 集合
Set<Integer> numberSet = pokerMap.keySet();
// 因为要将编号打乱顺序 所以 应该先进行转换到 list集合中
ArrayList<Integer> numberList = new ArrayList<Integer>();
numberList.addAll(numberSet);
// 打乱顺序
Collections.shuffle(numberList);

// 3 Complete three players alternate drawing cards, each with 17 cards, and the last three are reserved as hole cards

// 3. 1 Number of the deal

// Create three player number sets and a hole card number set

ArrayList noP 1 = new ArrayList();
ArrayList noP 2 = new ArrayList();
ArrayList noP 3 = new ArrayList();
ArrayList dipaiNo = new ArrayList();

// 3. 2 The number of the card issued
for (int i = 0; i <numberList.size(); i++) { // Get the number Integer no = numberList.get(i); // Issue the card // Set aside Hole card if (i >= 51) { dipaiNo.add(no); } else { if (i% 3 == 0) { noP 1 .add(no); } else if (i% 3 == 1) { noP 2 .add(no); } else { noP 3 .add(no); } } }















// 4 View the cards in the hands of the three people (sorted according to the size of the cards) and hole cards
// 4. 1 Sort the numbers in the
hands Collections.sort(noP 1 );
Collections.sort(noP 2 );
Collections.sort(noP 3 );
Collections.sort(dipaiNo);

// 4. 2 Convert the cards
// Create three player card sets and hole card sets
ArrayList player 1 = new ArrayList();
ArrayList player 2 = new ArrayList();
ArrayList player 3 = new ArrayList() ;
ArrayList dipai = new ArrayList();

// 4. 3 Conversion
for (Integer i: noP 1) { // 4. 4 Find the card according to the number pokerMap String card = pokerMap.get(i); // Add to the corresponding card set player 1 .add (card); }




for (Integer i : noP 2 ) {
String card = pokerMap.get(i);

player 2 .add(card);

}

for (Integer i : noP 3 ) {
String card = pokerMap.get(i);
player 3 .add(card);
}
for (Integer i : dipaiNo) {
String card = pokerMap.get(i);
dipai.add(card);
}

// 4. 5 View
System.out.println("Linghu Chong:"+player 1 );
System.out.println("Stone Breaking:"+player 2 );
System.out.println("Juma Chi:"+ player 3 );
System.out.println("The hole card:"+dipai);
}
}

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/108230694