JavaRush /Java Blog /Random EN /Convert Enum to String

Convert Enum to String

Published in the Random EN group
Today we will talk about working with string enumerations, and more specifically, with enumclasses in which interaction with string constants is organized. Convert Enum to String - 1

Using string enums

During application development, you periodically need to operate on a fixed set of string values. It could be anything. For example, a list of color codes supported by the application, or a list of devices with which our application is able to interact, seasons, etc. All this is a predefined set of string constants with a common structure, with which it is necessary to establish programmatic interaction at the Java code level. When it is necessary to interact with a predefined set of string (and not only) constants, the best solution is to write your own enumclass. Below are examples of converting enumto string.

Creating string enums

Let's create enuma class that stores a list of different environments for deploying the application, as well as the URL of each environment:
public enum Environment {
    PROD("https://release.application.com/"),
    TEST("https://test.application.com/"),
    AUTO_TEST("https://autotest.application.com/"),
    DEV("http://localhost:8080");

    private final String url;

    Environment(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }
}
In this class, we have defined 4 environments:
  • PROD- release
  • TEST- for manual testing
  • AUTO_TEST— environment for autotests
  • DEV- local for development and debugging
And also 4 URLs, for each of these environments. Let's pay attention to some important points.
  1. Each URL is a string constant of our enum: they are defined in parentheses next to each enumconstant.
  2. There must be a constructor that takes an argument of the same type as each enumconstant.
  3. The scope of the constructor is privateeither package private.
  4. It is necessary to define a variable - a class field that will store the string constants defined by us. For this field, you need to create a getter method in order to use the values ​​of string constants from outside.

Iterating over string enums

At this stage, we can already iterate through all the available enumvalues, as well as get the string constants associated with them. To get all the values ​​of any enumclass, you need to use the method values():
public class Main {
    public static void main(String[] args) {
        for (Environment env : Environment.values()) {
            System.out.println(env + " : " + env.getUrl());
        }
    }
}
Conclusion:

PROD : https://release.application.com/
TEST : https://test.application.com/
AUTO_TEST : https://autotest.application.com/
DEV : http://localhost:8080
As you can see from the example, to print the name of enumthe constant, we passed it to the method System.out.println, and to print the url associated with this constant, we used the getter we defined.

Getting string constant from enum

To get the value of any string constant, we can also call a getter on any enumconstant:
public class Main {
    public static void main(String[] args) {

        String prodUrl = Environment.PROD.getUrl();
        String devUrl = Environment.DEV.getUrl();

        System.out.println("Production url is: " + prodUrl);
        System.out.println("Development url is: " + devUrl);

    }
}
Conclusion:

Production url is: https://release.application.com/
Development url is: http://localhost:8080

Getting an enum constant by name

Sometimes it is necessary to get enuma constant by its string name. This is done using a method valueOf(String)that returns a constant by its name:
public class Main {
    public static void main(String[] args) {

        Environment prod = Environment.valueOf("PROD");
        Environment dev = Environment.valueOf("DEV");

        System.out.println("Production url is: " + prod.getUrl());
        System.out.println("Development url is: " + dev.getUrl());

    }
}
Conclusion:

Production url is: https://release.application.com/
Development url is: http://localhost:8080
But here caution is needed. If the method does not find enuma constant with the specified name, an exception will be thrown java.lang.IllegalArgumentException.

Convert String to Enum

Sometimes the need arises. Knowing the value of enum, get enumthe constant itself. Those. in our example, knowing a certain address, you need to get the corresponding Environmentconstant. There are several options for doing this. And all of them require refinement in enumthe class itself. Option 1. Search inside the class. You need to create a method that will take a string and compare it with all the values enum​​of the class. If it matches, the method will return the desired enum. For our example, you need to Environmentcreate the following method inside the class:
public static Environment getEnvByUrl(String url) {
    for (Environment env : values()) {
        // либо equalsIgnoreCase, на ваше усмотрение
        if (env.getUrl().equals(url)) {
            return env;
        }
    }

    // Либо просто вернуть null
    throw new IllegalArgumentException("No enum found with url: [" + url + "]");
}
Then we can get enumfrom a string like this:
public class Main {
    public static void main(String[] args) {
        String url = "http://localhost:8080";
        Environment env = Environment.getEnvByUrl(url);

        System.out.println("Environment name for url=[" + url + "] is: " + env);
    }
}
Conclusion:

Environment name for url=[http://localhost:8080] is: DEV
This approach has its downsides. Each time, to obtain enuma constant, you will have to iterate over all the values ​​​​and make a number of comparisons. The performance penalty in this case will be determined by the number of constants and the number of such operations. The second way to solve this problem does not have such a problem. Full Enumclass code:
public enum Environment {

    PROD("https://release.application.com/"),
    TEST("https://test.application.com/"),
    AUTO_TEST("https://autotest.application.com/"),
    DEV("http://localhost:8080");

    private final String url;

    Environment(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public static Environment getEnvByUrl(String url) {
        for (Environment env : values()) {
            if (env.getUrl().equals(url)) {
                return env;
            }
        }
        throw new IllegalArgumentException("No enum found with url: [" + url + "]");
    }
}
Option 2: Usage HashMap In this case, we create a map inside our enum and populate it once at compile time and then take values ​​from it:
public enum Environment {

    PROD("https://release.application.com/"),
    TEST("https://test.application.com/"),
    AUTO_TEST("https://autotest.application.com/"),
    DEV("http://localhost:8080");

    private final String url;

    Environment(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    // Создаем static final карту
    private static final Map<String, Environment> LOOKUP_MAP = new HashMap<>();

    // Заполняем её всеми значениями
    static {
        for (Environment env : values()) {
            LOOKUP_MAP.put(env.getUrl(), env);
        }
    }

    // Возвращаем Environment по строковому url
    public static Environment getEnvByUrl(String url) {
        return LOOKUP_MAP.get(url);
    }
}
In terms of use, both options are identical:
public class Main {
    public static void main(String[] args) {
        String url = "http://localhost:8080";
        Environment env = Environment.getEnvByUrl(url);

        System.out.println("Environment name for url=[" + url + "] is: " + env);
    }
}
Conclusion:

Environment name for url=[http://localhost:8080] is: DEV
But this method also has disadvantages. First, the code has become much larger. And secondly, HashMapwith all enumthe values ​​it will be stored in the application memory permanently. As you can see, everything has pros and cons. But given that enumnot so many values ​​are usually stored in classes, the disadvantages will be almost imperceptible. There is a nuance: if such an operation (getting a Java Enum by String value) is performed often, it is better to use the second option. You can learn more about this topic and Enumclasses in general on the CodeGym course. CodeGym students study Enumalready at the first lecture of the fifth level . Converting Enum to String - 2
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION