In Java, the Enum type is a very useful data type that can be used to represent enumeration constants. EnumMap is a special Map implementation in Java, which can only store key-value pairs of the Enum type. In this article, I will introduce the usage of EnumMap function and how to use EnumMap in Java for enumeration mapping operations.
- Basic usage of the EnumMap function
EnumMap
EnumMap<Weekday, String> enumMap = new EnumMap<>(Weekday.class); enumMap.put(Weekday.MONDAY, "星期一"); enumMap.put(Weekday.TUESDAY, "星期二"); enumMap.put(Weekday.WEDNESDAY, "星期三"); enumMap.put(Weekday.THURSDAY, "星期四"); enumMap.put(Weekday.FRIDAY, "星期五"); enumMap.put(Weekday.SATURDAY, "星期六"); enumMap.put(Weekday.SUNDAY, "星期日");
We first create an EnumMap object enumMap, and store each day of the week and the corresponding Chinese name into the EnumMap through the put method in EnumMap. In this way we have completed the creation and initialization of a basic EnumMap.
- Initialization of EnumMap function
In the above code example, we use the default constructor of EnumMap, which will automatically initialize all values to null. In fact, we can also use another constructor of EnumMap for initialization. This constructor will set an initial value and initialize all values in the EnumMap to this initial value. The following is the initialization sample code of the EnumMap function:
EnumMap<Weekday, String> enumMap = new EnumMap<>(Weekday.class); enumMap.put(Weekday.MONDAY, "星期一"); enumMap.put(Weekday.TUESDAY, "星期二"); enumMap.put(Weekday.WEDNESDAY, "星期三"); enumMap.put(Weekday.THURSDAY, "星期四"); enumMap.put(Weekday.FRIDAY, "星期五"); enumMap.put(Weekday.SATURDAY, "星期六"); enumMap.put(Weekday.SUNDAY, "星期日"); // 使用初始化值,将所有键值对的值都设置为"假期" EnumMapdefaultEnumMap = new EnumMap<>(Weekday.class); defaultEnumMap.putAll(Collections.singletonMap(null, "假期")); EnumMap enumMapWithDefaultValue = new EnumMap<>(defaultEnumMap); enumMapWithDefaultValue.putAll(enumMap);
In the above sample code, we used the Collections.singletonMap method to create a Map containing only one key-value pair, whose key is null and whose value is "holiday". Then, we use this Map as the initial value, create a new EnumMap object enumMapWithDefaultValue, and copy the key-value pairs in the previously created enumMap to this new EnumMap object.
This sample code allows us to understand how to use the EnumMap constructor to initialize, and how to use another Map as the initial value to create a new EnumMap.
- Traversal of EnumMap function
Traversing all elements in EnumMap is usually an essential operation. We can use iterators in Java to achieve this operation. The following is a sample code for traversing EnumMap:
EnumMap<Weekday, String> enumMap = new EnumMap<>(Weekday.class); enumMap.put(Weekday.MONDAY, "星期一"); enumMap.put(Weekday.TUESDAY, "星期二"); enumMap.put(Weekday.WEDNESDAY, "星期三"); enumMap.put(Weekday.THURSDAY, "星期四"); enumMap.put(Weekday.FRIDAY, "星期五"); enumMap.put(Weekday.SATURDAY, "星期六"); enumMap.put(Weekday.SUNDAY, "星期日"); // 使用迭代器遍历EnumMap中的所有键值对 Iterator> iterator = enumMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); Weekday key = entry.getKey(); String value = entry.getValue(); System.out.println(key + ": " + value); } // 使用foreach循环遍历EnumMap中的所有值 for (String value : enumMap.values()) { System.out.println(value); }
In this sample code, we use iterators in Java to traverse all key-value pairs in EnumMap. We first obtain the entrySet of the EnumMap, and then use the iterator returned by the entrySet to traverse all key-value pairs in sequence. For each key-value pair, we use the getKey method to get the key and the getValue method to get the value, and output them to the console.
We can also use a foreach loop to iterate through all the values in the EnumMap. Just use the enumeration type as a key to get the value. This method can avoid us frequently using the getKey method to obtain the key.
- Practical application of EnumMap function
In addition to the basic usage introduced above, the EnumMap function has many practical application scenarios.
4.1 Enumeration mapping operation
The most common use of EnumMap is to map enumeration types to other values. For example, in the following sample code, we map the enumeration type Weekday to a number (0-6):
public enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } // 使用EnumMap将Weekday枚举映射到数字 EnumMap<Weekday, Integer> enumMap = new EnumMap<>(Weekday.class); enumMap.put(Weekday.MONDAY, 0); enumMap.put(Weekday.TUESDAY, 1); enumMap.put(Weekday.WEDNESDAY, 2); enumMap.put(Weekday.THURSDAY, 3); enumMap.put(Weekday.FRIDAY, 4); enumMap.put(Weekday.SATURDAY, 5); enumMap.put(Weekday.SUNDAY, 6);
4.2 Enumeration type counter
In some cases, we need to implement a Counter to count the number of an enumeration type. EnumMap can easily implement this function. The sample code is as follows:
public enum Gender { MALE, FEMALE } // 使用EnumMap实现枚举类型计数器 EnumMap<Gender, Integer> genderCount = new EnumMap<>(Gender.class); genderCount.put(Gender.MALE, 0); genderCount.put(Gender.FEMALE, 0); List<Gender> genderList = Arrays.asList( Gender.MALE, Gender.MALE, Gender.MALE, Gender.FEMALE, Gender.FEMALE ); for (Gender gender : genderList) { genderCount.put(gender, genderCount.get(gender) + 1); } System.out.println("男性数量:" + genderCount.get(Gender.MALE)); System.out.println("女性数量:" + genderCount.get(Gender.FEMALE));
In the above sample code, we first created an EnumMap object genderCount to record the number of Gender types. Next, we use the put method in EnumMap to initialize the number of each Gender type to 0. Then, we use a List to simulate the gender list, and traverse the list to count the number of occurrences of each Gender. Finally, we output the number of males and females.
4.3 Enumeration type calculator
Similar to the enumeration type counter, EnumMap can also be used to implement addition and subtraction of enumeration types. For example, in the following sample code, we implemented a simple calculator to count the number of times a certain English letter appears in a certain word:
public enum Letter { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z } // 使用EnumMap实现枚举类型计算器 EnumMap<Letter, Integer> letterCount = new EnumMap<>(Letter.class); for (Letter letter : Letter.values()) { letterCount.put(letter, 0); } String word = "Hello, World!"; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (c >= 'A' && c <= 'Z') { Letter letter = Letter.valueOf(String.valueOf(c)); letterCount.put(letter, letterCount.get(letter) + 1); } } for (Letter letter : Letter.values()) { if (letterCount.get(letter) > 0) { System.out.println(letter + ": " + letterCount.get(letter)); } }
In the above sample code, we first created An EnumMap object letterCount, used to record the number of occurrences of each letter. We then use a for loop to iterate over the Letter enumeration type, setting the initial value of each letter to 0. Next, we defined a string word to simulate words. We iterate through each character in word and determine whether it is an uppercase letter. If it is an uppercase letter, we use the Letter.valueOf method to convert it to a Letter type, and accumulate the corresponding number of Letter types in letterCount. Finally, we iterate over the Letter enumeration type and output the letters whose occurrences are greater than 0 and the corresponding times.
Summary
In this article, we introduced the basic usage, initialization, traversal, practical application, etc. of the EnumMap function. EnumMap is a very practical Map implementation in Java. It can be used well with the Enum type to implement enumeration mapping, enumeration type statistics, calculators and other applications. Mastering the use of EnumMap will help improve the development efficiency and code quality of Java programs.
The above is the detailed content of How to use the EnumMap function in Java for enumeration mapping operations. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools