Home Java javaTutorial What is a Map collection? Characteristics of Map collections

What is a Map collection? Characteristics of Map collections

Jun 20, 2017 am 10:15 AM
collections parameter variable gather

Characteristics of Map collection:
1. It is a double-column collection. When assigning values, key and value must be assigned at the same time.
2. It is an unordered collection (storing and removing elements) The order may be inconsistent)
3. The key value cannot be repeated, but the value can be repeated
4. One key can only correspond to one vlaue
5. When defining a collection, the data type key and value can use the same data type. You can also use different data types

Characteristics of Map collection
java.util.MapInterface: Collection, which is a two-column collection

The first way to traverse a Map collection
The first way to traverse a Map collection: to find a value through a key
There is a method in the Map collection: keySet
Set keySet() Returns a Set view of the keys contained in this map. Store the keys in the Map collection into a Set collection
Steps to traverse the Map collection:
1. Define a Map collection and add elements to the collection
2. Call the Map collection The method keySet in the Map collection stores the keys in the Map collection into a Set collection
3. Traverse the Set collection and obtain all the keys in the Map collection
4. Use the get method of the Map collection to search through the obtained keys Value

 1 public static void main(String[] args) { 2         //1.定义一个Map集合,往集合中添加元素 3         Map<String,String> map = new HashMap<String,String>(); 4         map.put("a", "1"); 5         map.put("b", "2"); 6         map.put("c", "3"); 7         map.put("d", "4"); 8         //2.调用Map集合中的方法keySet,把Map集合中的健存储到一个Set集合中 9         Set<String> set = map.keySet();10         //System.out.println(set.getClass());11         //3.遍历Set集合,获取Map集合所有的健12         //使用迭代器遍历13         Iterator<String> it = set.iterator();14         while(it.hasNext()){15             String key = it.next();16             //4.通过获取到的健,使用Map集合的方法get查找值17             String value = map.get(key);18             System.out.println(key+"..."+value);19         }20         System.out.println("----------------");21         //使用增强for遍历22         for(String key : set){23             //4.通过获取到的健,使用Map集合的方法get查找值24             String value = map.get(key);25             System.out.println(key+"..."+value);26         }27         System.out.println("----------------");28         //使用增强for遍历29         for(String key : map.keySet()){30             //4.通过获取到的健,使用Map集合的方法get查找值31             String value = map.get(key);32             System.out.println(key+"..."+value);33         }34     }
Copy after login

The second way of Map collection traversal
The second way of Map collection traversal: the way of traversing key-value pairs
Map There is a method in the collection: entrySet
Set> entrySet() returns a Set view of the mapping relationships contained in this map.
Traversal steps:
1. Define a Map collection and add elements to the collection
2. Call the entrySet method in the Map collection to add each mapping relationship in the Map collection ( Marriage certificate) into the Set collection
3. Traverse the Set collection and obtain each mapping relationship Entry
4. Use the methods getKey and getValue in Entry to obtain the key sum Value

 1 public static void main(String[] args) { 2         //1.定义一个Map集合,往集合中添加元素 3         Map<String,String> map = new HashMap<String,String>(); 4         map.put("a", "1"); 5         map.put("b", "2"); 6         map.put("c", "3"); 7         map.put("d", "4"); 8         /* 9          * 2.调用Map集合中的方法entrySet,把Map集合中的每一个映射关系(结婚证)放入到Set集合中10          * 成员内部类的访问方式:外部类.内部类(Map.Entry)11          */12         Set<Map.Entry<String, String>> set = map.entrySet();13         //3.遍历Set集合,获取每一个映射关系Entry<K,V>14         //使用迭代器遍历Set集合15         Iterator<Map.Entry<String, String>> it = set.iterator();16         while(it.hasNext()){17             Map.Entry<String, String> entry = it.next();18             //4.使用Entry<K,V>中的方法getKey和getValue获取健和值19             String key = entry.getKey();20             String value = entry.getValue();21             System.out.println(key+"..."+value);22         }23         System.out.println("---------------------");24         //使用增强for遍历Set集合25         for(Map.Entry<String, String> entry:set){26             //4.使用Entry<K,V>中的方法getKey和getValue获取健和值27             String key = entry.getKey();28             String value = entry.getValue();29             System.out.println(key+"..."+value);30         }31         System.out.println("---------------------");32         //使用增强for遍历Set集合33         for(Map.Entry<String, String> entry:map.entrySet()){34             //4.使用Entry<K,V>中的方法getKey和getValue获取健和值35             String key = entry.getKey();36             String value = entry.getValue();37             System.out.println(key+"..."+value);38         }39     }
Copy after login

HashMap stores custom type key value
HashMap stores custom type key value
Custom type as the value of Map collection
Custom type as Map Keys of collections

Remember: when custom types override hashCode and equals
1. Use HashSet to store custom types
2. Use HashMap collections, and use custom types for keys

Hashtable
Map implementation class Hashtable
The underlying data structure is a hash table, the characteristics are the same as hashMap
Hashtable is a thread-safe collection and runs slowly
HashMap is a thread-unsafe collection and runs fast

The fate of Hashtable is the same as Vector. Starting from JDK1.2, it was replaced by the more advanced HashMap

HashMap allows the storage of null values. null key
hashtable is not allowed to store null values, null key

Hashtable His children, subclass Properties are still active in the development stage

LinkedHashMap collection features
java.util.LinkedHashMap extends HashMap implements Map
LinkedHashMap collection features:
1. Hash table + linked list: doubly linked list, which can guarantee the iteration order
2.Key cannot be repeated


Collections
java.util.Collections: Tool class for operating Collection collections
The methods in the tool class are all static methods and can be used directly through the class name

public static void sort(List list) // Sorting of collection elements
public static void shuffle(List list) // The storage location of collection elements is shuffled

Variable Parameter
New features that appeared after JDK1.5
Prerequisite for use: The data type of the method parameter is determined, but the number of parameters is uncertain

Using format:
Modifier return value type method name (data type...variable name){
}
...represents that the method can receive multiple parameters of the same data type
The bottom layer of variable parameters can be regarded as It is an array

Notes on variable parameters:
1. A method parameter can only use one variable parameter
2. If the method has multiple parameters , variable parameters must be written at the end of the parameter list

 1 public static int add(int...arr){ 2         System.out.println(arr);//[I@104c575 3         System.out.println(arr.length); 4         int sum = 0; 5         //遍历可变参数-->遍历数组 6         for (int i : arr) { 7             sum +=i; 8         } 9         10         return sum;11     }
Copy after login

static import
JDK1.5 new feature, static import
Reduce development time Code amount
Standard writing method, can only be used when importing a package
import static java.lang.System.out; At the end, it must be a static member

package cn.itcast.demo05;

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

  1 /*  2  * 带排序功能的斗地主案例:  3  *     1.准备牌  4  *     2.洗牌  5  *     3.发牌  6  *     4.排序  7  *     5.看牌  8  */  9 public class DouDiZhu { 10     public static void main(String[] args) { 11         //1.准备牌 12         //创建存储序号和拍面值的Map集合 13         HashMap<Integer,String> poker = new HashMap<Integer, String>(); 14         //创建存储序号的List集合 15         ArrayList<Integer> pokerNumber = new ArrayList<Integer>(); 16         //创建序号的数组 17         String[] numbers = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"}; 18         //创建花色数组 19         String[] colors = {"?","?","?","?"}; 20         //先把大王和小王存储到集合中 21         int index = 0; 22         poker.put(index, "大王"); 23         pokerNumber.add(index); 24         index++; 25         poker.put(index, "小王"); 26         pokerNumber.add(index); 27         index++; 28          29         //使用循环嵌套遍历两个数组,组成52张牌 30         for (String number : numbers) { 31             for (String color : colors) { 32                 //把组合包的牌添加到集合中 33                 poker.put(index, color+number); 34                 pokerNumber.add(index); 35                 index++; 36             } 37         } 38         //System.out.println(poker); 39         //System.out.println(pokerNumber); 40          41         //2.洗牌:洗的是牌的序号 42         //使用Collections中的方法shuffle 43         Collections.shuffle(pokerNumber); 44         //System.out.println(pokerNumber); 45          46         /* 47          * 3.发牌:发的也是牌的序号 48          *     a.定义4个集合存储3个玩家和1个底牌 49          *     b.遍历存储序号的List集合 50          *     c.使用list集合的索引%进行判断进行发牌 51          *     注意:先判断底牌 52          */ 53         //a.定义4个集合存储3个玩家和1个底牌 54         ArrayList<Integer> player01 = new ArrayList<Integer>(); 55         ArrayList<Integer> player02 = new ArrayList<Integer>(); 56         ArrayList<Integer> player03 = new ArrayList<Integer>(); 57         ArrayList<Integer> diPai = new ArrayList<Integer>(); 58          59         //b.遍历存储序号的List集合 60         for(int i=0; i<pokerNumber.size(); i++){ 61             //定义变量,接收排的序号 62             int number = pokerNumber.get(i); 63             //c.使用list集合的索引%进行判断进行发牌 64             if(i>=51){ 65                 //存储底牌 66                 diPai.add(number); 67             }else if(i%3==0){ 68                 //给玩家1发牌 69                 player01.add(number); 70             }else if(i%3==1){ 71                 //给玩家2发牌 72                 player02.add(number); 73             }else if(i%3==2){ 74                 //给玩家3发牌 75                 player03.add(number); 76             } 77         } 78         /*System.out.println(player01); 79         System.out.println(player02); 80         System.out.println(player03); 81         System.out.println(diPai);*/ 82          83         //4.排序 84         //使用Collections中的方法sort 85         Collections.sort(player01); 86         Collections.sort(player02); 87         Collections.sort(player03); 88         Collections.sort(diPai); 89          90         /*System.out.println(player01); 91         System.out.println(player02); 92         System.out.println(player03); 93         System.out.println(diPai);*/ 94          95         /* 96          * 5.看牌 97          */ 98         //调用看牌方法 99         lookPoker("刘德华",player01, poker);100         lookPoker("周润发",player02, poker);101         lookPoker("周星驰",player03, poker);102         lookPoker("底牌",diPai, poker);103     }104     105     /*106      * 定义一个看牌的方法107      * 返回值类型:void108      * 方法名:lookPoker109      * 参数列表:玩家和底牌的集合,存储排的Map集合110      * 使用查表法看牌:111      *     遍历List集合,获取Map集合key,使用key去Map集合中查找value112      */113     public static void lookPoker(String name,ArrayList<Integer> list,HashMap<Integer,String> map){114         System.out.print(name+":");115         //遍历List集合,获取Map集合key116         for (Integer key : list) {117             //使用key去Map集合中查找value118             String value = map.get(key);119             System.out.print(value+" ");120         }121         System.out.println();//换行122     }123 }
Copy after login

The above is the detailed content of What is a Map collection? Characteristics of Map collections. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

i9-12900H parameter evaluation list i9-12900H parameter evaluation list Feb 23, 2024 am 09:25 AM

i9-12900H is a 14-core processor. The architecture and technology used are all new, and the threads are also very high. The overall work is excellent, and some parameters have been improved. It is particularly comprehensive and can bring users Excellent experience. i9-12900H parameter evaluation review: 1. i9-12900H is a 14-core processor, which adopts the q1 architecture and 24576kb process technology, and has been upgraded to 20 threads. 2. The maximum CPU frequency is 1.80! 5.00ghz, which mainly depends on the workload. 3. Compared with the price, it is very suitable. The price-performance ratio is very good, and it is very suitable for some partners who need normal use. i9-12900H parameter evaluation and performance running scores

C++ function parameter type safety check C++ function parameter type safety check Apr 19, 2024 pm 12:00 PM

C++ parameter type safety checking ensures that functions only accept values ​​of expected types through compile-time checks, run-time checks, and static assertions, preventing unexpected behavior and program crashes: Compile-time type checking: The compiler checks type compatibility. Runtime type checking: Use dynamic_cast to check type compatibility, and throw an exception if there is no match. Static assertion: Assert type conditions at compile time.

Why is it difficult to implement collection-like functions in Go language? Why is it difficult to implement collection-like functions in Go language? Mar 24, 2024 am 11:57 AM

It is difficult to implement collection-like functions in the Go language, which is a problem that troubles many developers. Compared with other programming languages ​​such as Python or Java, the Go language does not have built-in collection types, such as set, map, etc., which brings some challenges to developers when implementing collection functions. First, let's take a look at why it is difficult to implement collection-like functionality directly in the Go language. In the Go language, the most commonly used data structures are slice and map. They can complete collection-like functions, but

C++ program to find the value of the inverse hyperbolic sine function taking a given value as argument C++ program to find the value of the inverse hyperbolic sine function taking a given value as argument Sep 17, 2023 am 10:49 AM

Hyperbolic functions are defined using hyperbolas instead of circles and are equivalent to ordinary trigonometric functions. It returns the ratio parameter in the hyperbolic sine function from the supplied angle in radians. But do the opposite, or in other words. If we want to calculate an angle from a hyperbolic sine, we need an inverse hyperbolic trigonometric operation like the hyperbolic inverse sine operation. This course will demonstrate how to use the hyperbolic inverse sine (asinh) function in C++ to calculate angles using the hyperbolic sine value in radians. The hyperbolic arcsine operation follows the following formula -$$\mathrm{sinh^{-1}x\:=\:In(x\:+\:\sqrt{x^2\:+\:1})}, Where\:In\:is\:natural logarithm\:(log_e\:k)

How to adjust the rounded corners of win10 search box How to adjust the rounded corners of win10 search box Jan 15, 2024 pm 03:12 PM

There has been news about the rounded corners of the win10 search box for a long time, but it has never been implemented. We can generally use the registry to experience the rounded corners of the win10 search box. So let's take a look at the tutorial on the rounded corners of the win10 search box. Bar. Win10 search box variable rounded corners: 1. Open the search box, enter regedit, and enter the registry. 2. Find this path in Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Search. 3. In the blank space, select New - DWORD (32-bit) value - Name the new key ImmersiveSearch - Number

Advanced usage of reference parameters and pointer parameters in C++ functions Advanced usage of reference parameters and pointer parameters in C++ functions Apr 21, 2024 am 09:39 AM

Reference parameters in C++ functions (essentially variable aliases, modifying the reference modifies the original variable) and pointer parameters (storing the memory address of the original variable, modifying the variable by dereferencing the pointer) have different usages when passing and modifying variables. Reference parameters are often used to modify original variables (especially large structures) to avoid copy overhead when passed to constructors or assignment operators. Pointer parameters are used to flexibly point to memory locations, implement dynamic data structures, or pass null pointers to represent optional parameters.

A Practical Guide to the Where Method in Laravel Collections A Practical Guide to the Where Method in Laravel Collections Mar 10, 2024 pm 04:36 PM

Practical Guide to Where Method in Laravel Collections During the development of the Laravel framework, collections are a very useful data structure that provide rich methods to manipulate data. Among them, the Where method is a commonly used filtering method that can filter elements in a collection based on specified conditions. This article will introduce the use of the Where method in Laravel collections and demonstrate its usage through specific code examples. 1. Basic usage of Where method

Common concurrent collections and thread safety issues in C# Common concurrent collections and thread safety issues in C# Oct 09, 2023 pm 10:49 PM

Common concurrent collections and thread safety issues in C# In C# programming, handling concurrent operations is a very common requirement. Thread safety issues arise when multiple threads access and modify the same data at the same time. In order to solve this problem, C# provides some concurrent collection and thread safety mechanisms. This article will introduce common concurrent collections in C# and how to deal with thread safety issues, and give specific code examples. Concurrent collection 1.1ConcurrentDictionaryConcurrentDictio

See all articles