- Convert String to Enum in Java
- 2. Sample Enum
- 3. Built-in Support
- 4. Iteration
- 5. Stream
- 6. Map
- 7. Summary
- Java enum with String
- Create java enum String
- Access enum by name
- Iteratve over all values of Enum with String constansts
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Java Enum tutorial with examples
- Java Enum with Strings
- Java Enum with Strings
- Can we create an enum with custom values in java?
- Custom values to the constants
- Example
- Output
Convert String to Enum in Java
In this quick tutorial, we’ll examine different ways of converting a String to an enum constant in Java.
To be more precise, we’ll retrieve an enum constant via its String property.
2. Sample Enum
Let’s first look at our sample enum:
public enum Direction < NORTH("north"), SOUTH("south"), WEST("west"), EAST("east"); private final String name; Direction(String name) < this.name = name; >public String getName() < return name; >>
The Direction enum contains one String property, name. It also defines four constants.
3. Built-in Support
By default, every enum class includes the static valueOf method. When given an enum constant name, valueOf returns the matched enum constant:
@Test public void shouldConvertFromEnumConstant()
Here, Direction.NORTH is retrieved from the String value NORTH.
However, when we want to retrieve Direction from its name property — not from its constant name — the built-in methods don’t help us. This means that we must write our own creator method that will take a String value and match it with one of the Direction constants.
4. Iteration
Firstly, we’ll create a static method that iterates over all constant values. In each iteration, it’ll compare the given value with the name property:
public static Direction fromValue(String givenName) < for (Direction direction : values()) < if (direction.name.equals(givenName)) < return direction; >> return null; >
Note that we’ll perform this iteration in each invocation.
5. Stream
We’ll now perform a similar iteration with Stream operators:
public static Direction fromValue(String givenName) < return Stream.of(values()) .filter(direction ->direction.name.equals(givenName)) .findFirst() .orElse(null); >
This method produces the same result as the previous one.
6. Map
So far we’ve iterated over the constant values and performed it for each method invocation. Iteration gives us more options during the comparison. For example, we can compare the name property and the given value ignoring the case. However, if we need only the exact matches, we can instead use a Map.
We must first construct a Map from the constant values:
private static Map nameToValue; static
Then we can implement our creator method:
public static Direction fromValueVersion3(String givenName)
7. Summary
In this tutorial, we’ve looked at how we can convert a String to an enum constant.
Finally, check out the source code for all examples over on Github.
Java enum with String
In this quick tutorial, how to create String constants using enum, convert String to enum etc.
You can go though complete enum tutorial here.
Let’s create java enum String constants.
Create java enum String
Access enum by name
You can simply use . operator to access enum but if you have string as enum name, then use of method.
Week day:TUESDAY
Week day:TUESDAY
Please note that valueOf method takes the String argument as case sensitive.
Exception in thread “main” java.lang.IllegalArgumentException: No enum constant org.arpit.java2blog.Weekdays.TUesDAY
at java.base/java.lang.Enum.valueOf(Enum.java:240)
at org.arpit.java2blog.Weekdays.valueOf(Weekdays.java:1)
at org.arpit.java2blog.JavaEnumStringMain.main(JavaEnumStringMain.java:7)
Iteratve over all values of Enum with String constansts
You can simply iterate over all String constants using values method.
Let’s give an index to each week days with 1 to 5.You can simply change above enum as below.
Access the index of any weekdays
That’s all about Java enum String.
Was this post helpful?
Share this
Related Posts
Author
Related Posts
Java Enum tutorial with examples
Table of ContentsConstructor:Methods:Declaration :Comparison and Switch case:Example: Java Enum is special data type which represents list of constants values. It is a special type of java class. It can contain constant, methods and constructors etc. Lets see example to understand better Let’s say we get three types of issues which require different SLA to get […]
Java Enum with Strings
In this guide to Java enum with string values, learn to create enum using strings, iterate over all enum values, get enum value and perform a reverse lookup to find an enum by string parameter.
We should always create enum when we have a fixed set of related constants. Enums are inherently singleton, so they provide better performance.
1. Creating Enum with Strings
Java program to create an enum with strings. The given enum contains deployment environments and their respective URLs. URLs are passed to the enum constructor for each enum constant.
public enum Environment < PROD("https://prod.domain.com:1088/"), SIT("https://sit.domain.com:2019/"), CIT("https://cit.domain.com:8080/"), DEV("https://dev.domain.com:21323/"); private String url; Environment(String envUrl) < this.url = envUrl; >public String getUrl() < return url; >>
2. Iterating over Enum Constants
To iterate over enum list, use values() method on enum type which returns all enum constants in an array.
//Get all enums for(Environment env : Environment.values())
PROD :: https://prod.domain.com:1088/ SIT :: https://sit.domain.com:2019/ CIT :: https://cit.domain.com:8080/ DEV :: https://dev.domain.com:21323/
To get a single enum value (e.g., get production URL from enum constant), use the getUrl() method that we created.
String prodUrl = Environment.PROD.getUrl(); System.out.println(prodUrl);
If we want to get enum constant using its name, then we should use valueOf() method.
Environment sitUrl = Environment.valueOf("SIT"); System.out.println(sitUrl.getUrl());
5. Reverse Lookup – Get Enum Name from Value
We will often have the value of enum with us, and we will need to get the enum name by its value. This is achieved using a reverse lookup.
enum Environment < PROD("https://prod.domain.com:1088/"), SIT("https://sit.domain.com:2019/"), CIT("https://cit.domain.com:8080/"), DEV("https://dev.domain.com:21323/"); private String url; Environment(String envUrl) < this.url = envUrl; >public String getUrl() < return url; >//****** Reverse Lookup ************// public static Optional get(String url) < return Arrays.stream(Environment.values()) .filter(env ->env.url.equals(url)) .findFirst(); > >
To use the reverse lookup in the application code, use enum.get() method.
String url = "https://sit.domain.com:2019/"; Optional env = Environment.get(url); System.out.println(env.get());
Java Enum with Strings
In this guide to Java enum with string values, learn to create enum using strings, iterate over all enum values, get enum value and perform a reverse lookup to find an enum by string parameter.
We should always create enum when we have a fixed set of related constants. Enums are inherently singleton, so they provide better performance.
1. Creating Enum with Strings
Java program to create an enum with strings. The given enum contains deployment environments and their respective URLs. URLs are passed to the enum constructor for each enum constant.
public enum Environment < PROD("https://prod.domain.com:1088/"), SIT("https://sit.domain.com:2019/"), CIT("https://cit.domain.com:8080/"), DEV("https://dev.domain.com:21323/"); private String url; Environment(String envUrl) < this.url = envUrl; >public String getUrl() < return url; >>
2. Iterating over Enum Constants
To iterate over enum list, use values() method on enum type which returns all enum constants in an array.
//Get all enums for(Environment env : Environment.values())
PROD :: https://prod.domain.com:1088/ SIT :: https://sit.domain.com:2019/ CIT :: https://cit.domain.com:8080/ DEV :: https://dev.domain.com:21323/
To get a single enum value (e.g., get production URL from enum constant), use the getUrl() method that we created.
String prodUrl = Environment.PROD.getUrl(); System.out.println(prodUrl);
If we want to get enum constant using its name, then we should use valueOf() method.
Environment sitUrl = Environment.valueOf("SIT"); System.out.println(sitUrl.getUrl());
5. Reverse Lookup – Get Enum Name from Value
We will often have the value of enum with us, and we will need to get the enum name by its value. This is achieved using a reverse lookup.
enum Environment < PROD("https://prod.domain.com:1088/"), SIT("https://sit.domain.com:2019/"), CIT("https://cit.domain.com:8080/"), DEV("https://dev.domain.com:21323/"); private String url; Environment(String envUrl) < this.url = envUrl; >public String getUrl() < return url; >//****** Reverse Lookup ************// public static Optional get(String url) < return Arrays.stream(Environment.values()) .filter(env ->env.url.equals(url)) .findFirst(); > >
To use the reverse lookup in the application code, use enum.get() method.
String url = "https://sit.domain.com:2019/"; Optional env = Environment.get(url); System.out.println(env.get());
Can we create an enum with custom values in java?
Enumeration (enum) in Java is a datatype which stores a set of constant values (Strings in general). You can use enumerations to store fixed values such as days in a week, months in a year etc.
Custom values to the constants
Instead of declaring just string constants in an enum, you can also have values to these constants as −
Whenever, you need to assign custom values to the constants of an enum −
- To hold the value of each constant you need to have an instance variable (generally, private).
- You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s).
- The initialization should be done only once. Therefore, the constructor must be declared private or default.
- To returns the values of the constants using an instance method(getter).
Example
In the following Java example, we are defining an enum with name Vehicles and declaring five constants representing the vehicle names with their prices as values.
enum Vehicles < //Constants with values ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable private int price; //Constructor to initialize the instance variable Vehicles(int price) < this.price = price; >public int getPrice() < return this.price; >> public class EnumTest < public static void main(String args[]) < Vehicles vehicles[] = Vehicles.values(); for(Vehicles veh: vehicles) < System.out.println("Price of "+veh+" is: "+veh.getPrice()); >> >
Output
Price of ACTIVA125 is: 80000 Price of ACTIVA5G is: 70000 Price of ACCESS125 is: 75000 Price of VESPA is: 90000 Price of TVSJUPITER is: 75000