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

Converting Enum to String

Published in the Random EN group
Today we’ll talk about working with string enumerations, and more specifically, with enumclasses that organize interaction with string constants. Converting Enum to String - 1

Using String Enumerations

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 can interact, seasons, etc. All this is a predefined set of string constants with a common structure, with which it is necessary to establish program interaction at the Java code level. When you need to interact with a predefined set of string (and other) constants, the best solution is to write your own enumclass. Below we will look at examples of conversion enumto string.

Creating String Enumerations

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 in our enumeration: 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 we have defined. You must create a getter method for this field in order to use the values ​​of string constants externally.

Iterating over string enumerations

At this stage, we can already iterate over all available enumvalues, as well as get 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 can be seen 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 a 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 enum constant by name

Sometimes it is necessary to get enuma constant by its string name. This is done using the method valueOf(String), which 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 caution is needed here. If the method does not find enuma constant with the specified name, an exception will be thrown java.lang.IllegalArgumentException.

Converting String to Enum

Sometimes the opposite need arises. Knowing the value enum, get enumthe constant itself. Those. in our example, knowing a certain address, you need to get the corresponding Environmentconstant. There are several options to do this. And all of them require improvement in enumthe class itself. Option 1. Enumeration inside the class. You need to create a method that will accept a string and compare it with all the values enum​​of the class. If there is a match, the method will return the desired enumeration. For our example, we 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 the 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 through all the values ​​and make a certain number of comparisons. The performance penalty in this case will be determined by the number of constants and the number of similar operations. The second method of solving this problem does not have this 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 the 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. Firstly, there is much more code. And secondly, HashMapall enumvalues ​​will be stored in the application memory permanently. As you can see, everything has pros and cons. But considering that enumclasses usually store not so many values, the disadvantages will be almost invisible. There is a caveat: if such an operation (getting a Java Enum by String value) is performed frequently, it is better to use the second option. You can learn more about this topic and Enumclasses in general in the JavaRush course. Students learn JavaRush 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