Java string to enum constant

Conversion of String to Enum in Java

Hey Everyone! In this article, we will learn how to convert a string to an enum data type in Java.

Enum in Java

Enum is a special data type in Java in which it’s field consists of a fixed set of constants.
Enum is declared using the keyword ‘enum’ in java.
It was introduced in java 1.5.
Example:-

It can be accessed as follows:-

Directions dr = Directions.NORTH;

Note that the constants included in the enum field are always written in CAPITAL (a certain writing convention is followed).

String to Enum

Now consider a case in which the string that is accepted in the code is to be converted to enum data type in java.
For that, the value of the method is used that is defined for enum data types.
The declaration of the method is as follows:-
public static T valueOf(String str)

Читайте также:  Как вывести модуль питон

This method accepts a string passed as a parameter and then converts it to the corresponding enum data type constant.
The IllegalArgumentException exception is thrown if no corresponding enum data type is found.

Thus the string that is passed as a parameter to the value of static method should match to the corresponding enum data type defined in its fields

Now Let’s have a look at the code:-

Java program to convert String to Enum in Java

package stringtoenum; import java.util.Scanner; enum Directions < NORTH, SOUTH, EAST, WEST >public class StringToEnum < public static void main(String[] args) < StringToEnum ste = new StringToEnum(); Scanner sc = new Scanner(System.in); String str; System.out.println("Enter string "); str = sc.nextLine(); ste.convert(str); >public static void convert(String str) < Directions dr = Directions.valueOf(str.toUpperCase()); System.out.println("The corresponding enum constant is " +dr); >>
Enter string WesT The corresponding enum constant is WEST

I hope you have understood the article.
If you have any suggestion feel free to comment down below.

Источник

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.

Источник

How to Convert String to Enum Type in Java?

The “String” is converted into an “Enum” type for accepting user inputs to enforce valid and predefined options. It provides better control and error handling in your application. While working with external data sources or APIs that provide values as strings, converting these strings to corresponding enum values. It allows for better integration and type safety in the Java code.

This article demonstrates the procedure for converting String-type data to the corresponding Enum type in Java.

How to Convert String to Enum Type in Java?

In Java, converting String to Enum type provides type safety by ensuring that only valid values defined in the enum class can be assigned. It enhances the readability and maintainability of the code. In real-time projects, this process is utilized for API integration, input validation, and for configuration parsing.

Follow the below methods to get detailed knowledge about the process of converting a string to an enum in Java:

Method 1: Using the valueOf() Method

The “valueOf()” method provides a straightforward way to convert a String representation to an enum constant and there is no need for manual checks as well. Moreover, by using it the compiler ensures type safety during the conversion process by validating that the string matches the name of an existing enum constant. It can be used for parsing user inputs, serialization, and deserialization.

Visit the below code for converting a string to an enum in Java using the “valueOf()” method:

public class StringToEnum {
enum Color {
RED , GREEN , BLUE
}
public static void main ( String [ ] args ) {
String colString = «RED» ;
// Convert the String to the Color enum
Color color = Color. valueOf ( colString ) ;
System. out . println ( «Converted Enum: » + color ) ;
}
}

Description of the above code:

  • First, declare an “enum” type of “Color” that represents a fixed set of constants which are color names in our case.
  • Next inside the “main()” method, store the value of “RED” in a String type variable named “colString”.
  • After that, pass the “colString” inside the “valueOf()” method and store it in an instance of the enum “Color”. This converts the variable type from String to Enum.
  • In the end, display the created instance that has the name “color” on the console.

After the end of the compilation phase:

The output displays that the provided string type variable has been converted into an enum type.

Method 2: Using a Custom Mapping or Lookup Table

By creating a custom mapping or lookup table, the programmer can associate String values with their corresponding Enum values. It enables custom mappings and conversions that may not follow the standard naming conventions of enum. This approach provides flexibility and control over the conversion process.

Visit the below code for practical implementation:

import java. util . HashMap ;
import java. util . Map ;
enum Color {
CYAN , MAGENTA , YELLOW , BLACK
}
public class StringToEnumExample {
private static final Map < String , Color >colorMap = new HashMap <> ( ) ;
static {
colorMap. put ( «c» , Color. CYAN ) ;
colorMap. put ( «m» , Color. MAGENTA ) ;
colorMap. put ( «y» , Color. YELLOW ) ;
colorMap. put ( «k» , Color. BLACK ) ;
}
public static void main ( String [ ] args ) {
String colorString = «y» ;
Color color = colorMap. get ( colorString ) ;
if ( color != null ) {
System. out . println ( «String is Converted into Enum: » + color ) ;
} else {
System. out . println ( «Invalid color string» ) ;
}
}
}

Description of the above code:

  • First, create an enum named “Color” that stores different constants each defining color name.
  • Next, a “HashMap” named “colorMap” is used inside the “main()” method.
  • Then, statically insert values in the “colorMap” by utilizing the “put()” method. The values are provided in key-value pair form, where the string values are considered as key and enum constants as their corresponding values.
  • After that, select random string values and store them in a variable named “colorString”.
  • Next, use the “get()” method on the colorMap. It retrieves the corresponding color based on the provided colorString.
  • If the “colorString” is valid and has a mapping in the “colorMap”, the corresponding “Color” enum value gets printed and vice versa.

After the end of the compilation phase:

The output shows the corresponding enum value for the provided string printed out on the console.

Conclusion

To convert String to Enum type in Java, use the valueOf() method with the enum class name and the string value as arguments. In Java, the programmers convert String to an Enum to promote type safety, readability, and maintainability of code. In addition, providing better control and validation for external data, user input, and integration with APIs. It helps in reducing the chance of errors and simplifies the handling of string-based representations in enum-based scenarios.

About the author

Abdul Moeed

I’m a versatile technical author who thrives on adaptive problem-solving. I have a talent for breaking down complex concepts into understandable terms and enjoy sharing my knowledge and experience with readers of all levels. I’m always eager to help others expand their understanding of technology.

Источник

Java — convert String to Enum object

Root-ssh

public class Example1 < enum ColorEnum < RED, GREEN, BLUE >public static void main(String[] args) < String color = "BLUE"; // we use valueOf on our enum class ColorEnum colorEnum = ColorEnum.valueOf(color); System.out.println(colorEnum); // BLUE >>

In java we can simply convert String to enum by using .valueOf() method on our Enum class.

  • letter size must be the same
  • if uppercase letters then we need to use uppercase
  • if lowercase letters then we need to use lowercase
  • no spaces
  • no white spaces

1. Documentation — Enum valueOf() method

valueOf is static method that takes only one parameter and returns enum constant.
Usage example:
ColorEnum colorEnum = ColorEnum.valueOf(«BLUE»);

2. Using Enum value() and String.toUpperCase()

public class Example2 < enum ColorEnum < RED, GREEN, BLUE >public static void main(String[] args) < String color = "blue"; color = color.toUpperCase(); ColorEnum colorEnum = ColorEnum.valueOf(color); System.out.println(colorEnum); // BLUE >>

3. Case with No enum constant

public class Example3 < enum ColorEnum < RED, GREEN, BLUE >public static void main(String[] args) < String color = "WHITE"; ColorEnum colorEnum = ColorEnum.valueOf(color); System.out.println(colorEnum); >>
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.dirask.Example3.ColorEnum.WHITE at java.lang.Enum.valueOf(Enum.java:238)

Common mistakes

Merged questions

Источник

How to convert a String to an enum in Java?

The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.

Example

Let us create an enum with name Vehicles with 5 constants representing models of 5 different scoters with their prices as values, as shown below −

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; >//Static method to display the price public int getPrice() < return this.price; >>

The following Java program, accepts a String value from the user, converts it into an enum constant of the type Vehicles using the valueOf() method and, displays the value (price) of the selected constant.

public class EnumerationExample < public static void main(String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter]"); System.out.println("Enter the name of required scoter: "); String name = sc.next(); Vehicles v = Vehicles.valueOf(name.toUpperCase()); System.out.println("Price: "+v.getPrice()); >>

Output

Available scoters: [activa125, activa5g, access125, vespa, tvsjupiter] Enter the name of required scoter: activa125 Price: 80000

Источник

Оцените статью