SoFunction
Updated on 2025-04-14

Java enumeration class implements various implementation methods for Key-Value mapping

Preface

In Java development, enum (Enum) is a special class that can define a fixed set of constants. In practical applications, we often need to add extra attributes to enumeration constants and implement the mapping relationship of key-value. This article will introduce in detail the various ways in which Java enumeration classes implement key-value mapping, analyze their respective advantages and disadvantages, and give best practice suggestions in practical applications.

1. Basic implementation method

1.1 Add properties and constructor methods for enumerations

The most basic implementation method is to add key and value attributes to the enumeration and provide corresponding constructors and access methods.

public enum Status {
    ACTIVE("A", "Activation Status"),
    INACTIVE("I", "Inactive"),
    PENDING("P", "Waiting State");

    private final String key;
    private final String value;

    Status(String key, String value) {
         = key;
         = value;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }
}

Example of usage:

Status active = ;
("Key: " + () + ", Value: " + ());

advantage:

  • Achieve simple and intuitive
  • No additional data structure support required

shortcoming:

Inefficient search (need to traverse all enum values)

2. Efficient search for implementation methods

2.1 Using Static Map Cache

To improve search efficiency, static maps can be used to cache the mapping relationship between key and enum instances.

import ;
import ;

public enum Status {
    ACTIVE("A", "Activation Status"),
    INACTIVE("I", "Inactive");

    private final String key;
    private final String value;
    
    private static final Map<String, Status> BY_KEY = new HashMap<>();
    
    static {
        for (Status s : values()) {
            BY_KEY.put(, s);
        }
    }

    Status(String key, String value) {
         = key;
         = value;
    }

    public static Status fromKey(String key) {
        return BY_KEY.get(key);
    }
    
    public static String getValueByKey(String key) {
        Status status = fromKey(key);
        return status != null ?  : null;
    }
    
    // getters...
}

advantage:

  • High search efficiency (O(1) time complexity)
  • Suitable for situations where enumeration values ​​are large

shortcoming:

  • Requires extra memory space for storage Map
  • Static initialization may increase class loading time

2.2 Using Java 8 Stream API

Java 8 introduces the Stream API, which we can use to implement concise search logic.

public static Status fromKeyStream(String key) {
    return (())
            .filter(status -> ().equals(key))
            .findFirst()
            .orElse(null);
}

advantage:

  • Concise code
  • No additional data structure required

shortcoming:

  • Every lookup requires traversal (performance is not as good as Map cache)
  • Suitable for scenarios with fewer enumeration values ​​or infrequent searches

3. Advanced skills and best practices

3.1 Handling null and non-existent situations

In practical applications, we need to consider the case where the key is null or does not exist.

public static Status fromKeySafely(String key) {
    if (key == null) {
        return null;
    }
    return BY_KEY.get(key);
}

public static String getValueByKeySafely(String key) {
    Status status = fromKeySafely(key);
    return status != null ? () : "UNKNOWN";
}

3.2 Immutable Map Implementation

If you want the Map to be immutable, you can use:

private static final Map<String, Status> BY_KEY;
static {
    Map<String, Status> map = new HashMap<>();
    for (Status s : values()) {
        (, s);
    }
    BY_KEY = (map);
}

3.3 Combining enumeration and interface

Enumeration implementation interfaces can be made to provide more flexible designs:

public interface KeyValueEnum&lt;K, V&gt; {
    K getKey();
    V getValue();
}

public enum Status implements KeyValueEnum&lt;String, String&gt; {
    // Enumeration implementation...}

4. Performance comparison

The following table compares the performance characteristics of different implementation methods:

Implementation method Time complexity Space complexity Applicable scenarios
Basic implementation O(n) O(1) There are few enum values, and few searches are found frequently
Static Map Cache O(1) O(n) Many enumeration values, frequent searches
Stream API O(n) O(1) Java8+, simplicity of code is preferred

5. Practical application examples

5.1 Application in Spring Boot

Combined with Spring Boot, we can better combine enumeration with REST API:

@Getter
public enum ErrorCode implements KeyValueEnum&lt;Integer, String&gt; {
    SUCCESS(200, "success"),
    NOT_FOUND(404, "Resource does not exist"),
    SERVER_ERROR(500, "Server Error");

    private final Integer key;
    private final String value;
    
    //Construction method, etc...}

@RestController
public class ApiController {
    @GetMapping("/errors/[code]")
    public ResponseEntity&lt;String&gt; getErrorMessage(@PathVariable Integer code) {
        return (())
                .filter(e -&gt; ().equals(code))
                .findFirst()
                .map(e -&gt; (()))
                .orElse(().build());
    }
}

5.2 Interaction with the database

Common patterns for enumeration and database value conversion:

@Converter(autoApply = true)
public class StatusConverter implements AttributeConverter<Status, String> {
    @Override
    public String convertToDatabaseColumn(Status status) {
        return status != null ? () : null;
    }

    @Override
    public Status convertToEntityAttribute(String key) {
        return (key);
    }
}

6. Summary

  • Small enumeration: Just use basic implementation to keep the code simple
  • Large enumeration or high-frequency search: static Map cache is recommended
  • Java8+ environment: You can consider using the Stream API to implement concise code
  • Production environment: Be sure to deal with null and non-existent situations, consider using immutable maps

Enumerated key-value mapping is a common requirement in Java development. Choosing the appropriate implementation method can significantly improve the readability and performance of the code. Hope the various methods and best practices introduced in this article will be helpful to you.

Extended thinking: How to implement two-way search (find value through key, and key through value)? Readers can try to implement a two-way search enumeration tool class.

The above is the detailed content of various implementation methods for Java enumeration classes to implement Key-Value mapping. For more information about Java enumeration classes to implement Key-Value mapping, please pay attention to my other related articles!