Home >Java >javaTutorial >How to use the EnumMap function in Java for enumeration mapping operations
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.
EnumMap5020972f684133d4ac6a4986ae645516, V> is a generic class in Java, where K represents the enumeration type Key, V represents the value mapped to the key. After an EnumMap is created, its keys must come from the same enumeration type, and all values must be of the same type. The following is the basic usage 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, "星期日");
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.
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.
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.
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!