Java Enum valueOf

Java Enum valueOf

Java.lang.Enum.valueOf() Method – Tutorialspoint

Source: (tutorialspoint.com)

Java.lang.Enum.valueOf() Method – The java.lang.Enum.valueOf() method returns the enum constant of the specified enumtype with the specified name. The name must match exactly an identifier used

Declaration

Following is the declaration for java.lang.Enum.valueOf() method public static > T valueOf(Class enumType, String name)

Exception

IllegalArgumentException − if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type.

NullPointerException − if enumType or name is null.

How to get an enum value from a string value in Java?

Source: (stackoverflow.com)

Say I have an enum which is just public enum Blah { A, B, C, D } and I would like to find the enum value of a string, for example “A” which would be Blah.A. How would it be possible to do thi…

Kotlin Solution

Create an extension and then call valueOf(“value”) . If the type is invalid, you’ll get null and have to handle it Alternatively, you can set a default value, calling valueOf(“value”, MyEnum.FALLBACK) , and avoiding a null response. You can extend your specific enum to have the default be automatic Or if you want both, make the second:

Java Enum ValueOf Example – How to use

Source: (java67.com)

Java Programming tutorials and Interview Questions, book and course recommendations from Udemy, Pluralsight, Coursera, edX etc

Outline:

  • Java Enum ValueOf Example – How to use
  • valueOf Java Enum Example

Java Enum ValueOf Example – How to use

valueOf method of Java Enum is used to retrieve Enum constant declared in Enum Type by passing String in other words valueOf method is used to convert String to Enum constants . In this Java Enum valueOf example we will see how to use valueOf method in Java. valueOf method is implicitly available to all Java Enum because every enum in Java implicitly extends java.lang.Enum class. valueOf method of enum accepts exactly same String which is used to declare Enum constant to return that Enum constant. valueOf method is case-sensitive and invalid String will result in IllegalArgumentException . In short String passed to valueOf method of Java enum must be same to String returned by name() method like TrafficSigal.RED.name() returns RED and you should pass RED to valueOf() to get TrafficSignal.RED . This will be more clear will following Java Enum valueOf example. By the way its third tutorial on Enum in Java after previous post on Java Enum Swith Example and Java Enum toString example . If you have not read those tutorial you may find useful.a

Source: java67.com

valueOf Java Enum Example

Here is complete code example of valueOf method of Java Enum. In this enum example we have used a TrafficSignal Enum to demonstrate how we can retrieve Enum from String in Java .

/** * * Java program to show How to use valueOf method of Enum * to create enum. This is simple Enum valueOf example which * teaches how to use valueOf method. * * @author */ public class EnumValueOfExample { public static void main ( String args []) { //valueOf method returns Enum instance with name matching to String passed to valueOf TrafficSignal signal = TrafficSignal. valueOf ( “RED” ) ; System . out . println ( “name : ” + signal. name () + ” action : ” + signal. getAction ()) ; //Another Enum valueOf exampel signal = TrafficSignal. valueOf ( “GREEN” ) ; System . out . println ( “name : ” + signal. name () + ” action : ” + signal. getAction ()) ; //valueOf will throw IllegalArgumentException if we pass invalid String signal = TrafficSignal. valueOf ( “Green” ) ; } } enum TrafficSignal { RED ( “stop” ) , GREEN ( “start” ) , ORANGE ( “slow down” ) ; private String action ; public String getAction (){ return this . action ; } private TrafficSignal ( String action ){ this . action = action ; } } Output: name : RED action : stop name : GREEN action : start Exception in thread “main” java. lang . IllegalArgumentException : No enum const class test. TrafficSignal . Green at java. lang . Enum . valueOf ( Enum . java : 196 ) at test. TrafficSignal . valueOf ( EnumValueOfExample . java : 34 ) at test. CollectionTest . main ( EnumValueOfExample . java : 29 ) Java Result : 1 That’s all on this Java Enum valueOf example . See 10 Java enum Examples for more examples of enum in Java. In short enum valueOf is a useful method which is by default available to all enum constants and can be used to get Enum constants from String. Further Learning Complete Java Masterclass Java Fundamentals: The Java Language Java In-Depth: Become a Complete Java Engineer!

Source: java67.com

Java Enum valueOf() Method – Javatpoint

Source: (javatpoint.com)

Java Enum valueOf() Method with Examples on java, enum, clone(), compareTo(), equals(), finalize(), name(), hashCode(), ordinal(), toString(), valueOf() etc.

Outline:

  • Java Enum valueOf() Method
  • Example 1
  • Example 2
  • Javatpoint Services
  • Training For College Campus

Java Enum valueOf() Method

The valueOf() method of Enum class returns the enum constant(of defined enum type) along with the defined name.

Source: javatpoint.com

Example 1

enum Parts{ Skin, Muscles,Bones,Organs,Tissue; } public class Enum_valueOfMethodExample1 { public static void main(String[] args) { System.out.println(“The part which is exposed to the environment is :”); for(Parts part : Parts.values()){ int i = part.ordinal()+1; System.out.println(i+” “+part); } Parts part = Parts.valueOf(“Skin”); System.out.println(“\nAns: “+part); } } Test it Now

Output:

The part which is exposed to the environment is : 1 Skin 2 Muscles 3 Bones 4 Organs 5 Tissue Ans: Skin

Example 2

enum Flower{ Rose,Lily, Orchids, Sunflower,Jasmine; } public class Enum_valueOfMethodExample2 { public static void main(String[] args) { System.out.println(“The part which is exposed to the environment is :”); for(Flower flower : Flower.values()) { System.out.println(Flower.valueOf(” “)); } } } Test it Now

Output:

Exception in thread “main” java.lang.IllegalArgumentException: No enum constant com.javaTpoint.Flower. The part which is exposed to the environment is : atjava.lang.Enum.valueOf(Enum.java:238) atcom.javaTpoint.Flower.valueOf(Enum_valueOfMethodExample2.java:4) at com.javaTpoint.Enum_valueOfMethodExample2.main(Enum_valueOfMethodExample2.java:11)

Attaching Values to Java Enum

Source: (baeldung.com)

Explore features of the Java Enum implementation.

Outline:

  • Further Reading:
  • 1. Introduction
  • A Guide to Java Enums
  • 2. Using Java Enum as a Class
  • 4. Locating Java Enum Values
  • 5. Caching the Lookup Values
  • 6. Attaching Multiple Values
  • 7. Controlling the Interface
  • 7.2. Implementing an Interface
  • 8. Conclusion

Further Reading:

A quick and practical guide to the use of the Java Enum implementation, what it is, what problems it solves and how it can be used to implement commonly used design patterns.

1. Introduction

The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type-safe than constant literal variables like String or int.

However, enum values are required to be valid identifiers , and we’re encouraged to use SCREAMING_SNAKE_CASE by convention.

Given those limitations, the enum value alone is not suitable for human-readable strings or non-string values In this tutorial, we’ll use the enum‘s features as a Java class to attach the values we want.

A Guide to Java Enums

A quick and practical guide to the use of the Java Enum implementation, what it is, what problems it solves and how it can be used to implement commonly used design patterns.

Source: baeldung.com

2. Using Java Enum as a Class

We often create an enum as a simple list of values. For example, here are the first two rows of the periodic table as a simple enum:

Using the syntax above, we’ve created ten static, final instances of the enum named Element. While this is very efficient, we have only captured the element symbols. And while the upper-case form is appropriate for Java constants, it’s not how we normally write the symbols.

Furthermore, we’re also missing other properties of the periodic table elements, like the name and atomic weight.

Although the enum type has special behavior in Java, we can add constructors, fields, and methods as we do with other classes. Because of this, we can enhance our enum to include the values we need.

Source: baeldung.com

4. Locating Java Enum Values

Java provides a valueOf(String) method for all enum types. Thus, we can always get an enum value based on the declared name:

However, we may want to look up an enum value by our label field as well. To do that we can add a static method:

The static valueOfLabel() method iterates the Element values until it finds a match. It returns null if no match is found. Conversely, an exception could be thrown instead of returning null.

Let’s see a quick example using our valueOfLabel() method:

Source: baeldung.com

5. Caching the Lookup Values

We can avoid iterating the enum values by using a Map to cache the labels . To do this, we define a static final Map and populate it when the class loads:

As a result of being cached, the enum values are iterated only once , and the valueOfLabel() method is simplified.

As an alternative, we can lazily construct the cache when it is first accessed in the valueOfLabel() method. In that case, map access must be synchronized to prevent concurrency problems.

Source: baeldung.com

6. Attaching Multiple Values

The Enum constructor can accept multiple values . To illustrate, let’s add the atomic number as an int and the atomic weight as a float:

Similarly, we can add any values we want to the enum, such as the proper case symbols, “He”, “Li”, and “Be”, for example.

Moreover, we can add computed values to our enum by adding methods to perform operations.

Source: baeldung.com

7. Controlling the Interface

As a result of adding fields and methods to our enum, we’ve changed its public interface. Therefore, our code, which uses the core Enum name() and valueOf() methods, will be unaware of our new fields.

The static valueOf() method is already defined for us by the Java language. Therefore, we can’t provide our own valueOf() implementation.

Similarly, because the Enum.name() method is final, we can’t override it either As a result, there’s no practical way to utilize our extra fields using the standard Enum API. Instead, let’s look at some different ways to expose our fields.

Source: baeldung.com

7.2. Implementing an Interface

The enum type in Java can implement interfaces . While this approach is not as generic as the Enum API, interfaces do help us generalize.

Let’s consider this interface:

For consistency with the Enum.name() method, our label() method does not have a get prefix.

And, because the valueOfLabel() method is static, we do not include it in our interface.

Finally, we can implement the interface in our enum:

One benefit of this approach is that the Labeled interface can be applied to any class, not just enum types. Instead of relying on the generic Enum API, we now have a more context-specific API.

Source: baeldung.com

8. Conclusion

In this article, we’ve explored many features of the Java Enum implementation. By adding constructors, fields, and methods, we see that the enum can do a lot more than literal constants.

As always, the full source code for this article can be found over on GitHub

Fundamentals of Java Enum Types – SitePoint

Source: (sitepoint.com)

Java enum types make it easy to define a fixed number of constants. More than that, enums are full-blown classes and can have fields and methods.

Outline:

  • Table of Contents
  • Enum Fundamentals
  • Defining an Enum
  • Using an Enum
  • Switch Statements
  • Enums as a Class
  • Enums with Fields
  • Enums with Methods
  • Implementing interfaces
  • Summary
  • Valdio Veliu
  • Brief About OSGI
  • Step 2: Create Liferay Module
  • Step 4: Run Eclipse Build
  • Shaik Ismail

Table of Contents

Whatever code you’re working on, chances are you will sooner or later need a list of constants, like Monday, Tuesday, etc. for all weekdays or January, Februrary, etc. for all months. Java has you covered with enum types, usually only called enums, which make it exceedingly easy to define just that. In this article I will teach you everything you need to know to become a proficient user of Java enums.

Source: sitepoint.com

Enum Fundamentals

In its simplest form a Java enum is just a fixed number of constants that the developer defines while writing the code. (It could, for example, define all SitePoint channels.) Much like a class, an enum defines a type that can be used just about anywhere where classes and interfaces could be used, for example for fields, variables, and parameters.

Enums can actually be much more than mere constants, having their own attributes and methods, but I will come to that later. Seeing them as constants is a good way to get to know them.

Defining an Enum

An enum is defined similarly to how a class would be defined but uses the enum instead of the class keyword. The constant values are listed in the enum’s body (meaning within the curly braces). While not necessary, it is common to write the constants in all uppercase letters to make it easier to recognize them.

Now that we have a description for enums, it’s time for an example. Here is what an enum looks like that lists some of the SitePoint channels:

The elements inside the SitePointChannel enum are called enumeration constants.

Source: sitepoint.com

Using an Enum

Enumerations have a variety of features in Java. One of their core capabilities is that they can be used in identity comparisons and switch statements.

Enumeration constants can be compared for identity by using the relational operator . Here is an example of an if() condition, which in this case is always false.

Source: sitepoint.com

Switch Statements

Another very widely used feature of enumerations is the ability to control switch statements . Here is an example that prints the content of a given channel:

In switch statements, enumeration constants are used without their enumeration type name. This is due to the fact the enum type is implicitly specified in the switch expression. It is good practice to list all enum constants (even if some of them don’t do anything) and add a default branch, usually with an exception (in case a new constant gets added and someone misses the switch statement and doesn’t update it.)

Enums as a Class

With the basics of Java enums covered we can go beyond the interpretation of enums as a fixed number of constants. Enums are, in fact, much more like classes!

They can have fields and methods as well as implement interfaces and I will explain all of that in a minute. Even the enumeration constants are not that special – they are just public, static, and final members of their enum type. The only reason we don’t have to put public static final in is that the compiler fills it in for us.

The major differences towards regular classes is that they can not extend other classes (see below why) and can not be created with the new keyword (to keep the number of constants fixed).

Extending java.lang.Enum All enums implicitly extend java.lang.Enum . In Java, a class can only extend one parent and therefore an enum cannot extend any other class (but implement interfaces – see below).

Extending Enum means that every enum has a few methods that make it more usable:

Source: sitepoint.com

Enums with Fields

Java enumeration constants can have fields, which must be given a value at creation time. Keep in mind that as with instances of a regular class, each enumeration constant has its own fields. In order to define values, the enclosing type must have a constructor that accepts parameters. As I mentioned earlier, each enumeration constant is an object of its enumeration type, so a constructor is called for each of the enumeration constants. Fields and constructors (as well as methods) must be defined below the list of constants.

Let’s go through an example for this problem. Suppose we have the SitePointChannel enumeration with the list of channels and we need to add to each channel the number of published articles. I will declare a field for it:

So far, so good, but the field is never assigned a value. To do that we also need a constructor:

Unfortunately this does not compile because the constants are initiated with the no-args constructor that no longer exists. To fix this, we call the new constructor:

The same logic is true for multiple instance variables and different data types ( int double String

Source: sitepoint.com

Enums with Methods

Besides the basic method available to all enums you can add custom methods to add additional functionalities.

The following example demonstrates the usefulness of enums with methods. Previously in this article, I mentioned that the valueOf() method is case sensitive. The following solution will give an alternative solution to the valueOf() method without the limitations of case sensitivity, by creating our own method.

To make sure this solution works, run the following code snippet.

As you can see from the example, the valueOfIgnoreCase() function takes the string “jaVa” and returns the JAVA enum. This solution works for any combination of uppercase and lowercase characters of a string representing a SitePointChannel enum instance.

Source: sitepoint.com

Implementing interfaces

Given the ability to have fields and methods it makes sense that enums can also implement interfaces. This works exactly like it would in regular classes so there is little to be said about it.

Here’s a simple example:

Summary

That’s all on the fundamentals of Java enums. We saw that they can describe a fixed number of constants and how Enum ‘s methods values() valueOf(String)

name()

ordinal()

, and

compareTo(Enum)

can be used. But we also discovered that they are full-blown classes, which allow adding fields, creating methods, and implementing interfaces.

Java Enums

Source: (tutorials.jenkov.com)

A Java Enum is a type used specifically to represent sets of constants. A Java Enum can be used instead of static final int or String variables otherwise used to represents constants in Java applications. This Java Enum tutorial explains how to create and use Java Enums.

Outline:

  • Enums in if Statements
  • Enums in switch Statements
  • Enum Iteration
  • Running this Java code would print out all the enum values. Here is the output: HIGH MEDIUM LOW
  • Enum Fields
  • Enum Methods
  • Enum Abstract Methods
  • Enum Implementing Interface
  • EnumSet
  • EnumMap
  • Enum Miscellaneous Details

Enums in if Statements

Since Java enums are constants you will often have to compare a variable pointing to an enum constant against the possible constants in the enum type. Here is an example of using a Java enum in an if -statement: Level level = … //assign some Level constant to it if( level == Level.HIGH) { } else if( level == Level.MEDIUM) { } else if( level == Level.LOW) { } This code compares the level variable against each of the possible enum constants in the Level enum.

If one of the enum values occur more often than the others, checking for that value in the first if -statement will result in better performance, as less comparison on average are executed. This is not a big difference though, unless the comparisons are executed a lot.

Source: tutorials.jenkov.com

Enums in switch Statements

If your Java enum types contain a lot constants and you need to check a variable against the values as shown in the previous section, using a Java switch statement might be a good idea.

You can use enums in switch statements like this: Level level = … //assign some Level constant to it switch (level) { case HIGH : …; break; case MEDIUM : …; break; case LOW : …; break; } Replace the … with the code to execute if the level variable matches the given Level constant value. The code could be a simple Java operation, a method call etc.

Source: tutorials.jenkov.com

Enum Iteration

You can obtain an array of all the possible values of a Java enum type by calling its static values() method. All enum types get a static values() method automatically by the Java compiler. Here is an example of iterating all values of an enum: for (Level level : Level.values()) { System.out.println(level); }

Running this Java code would print out all the enum values. Here is the output: HIGH MEDIUM LOW

Notice how the names of the constants themselves are printed out. This is one area where Java enums are different than static final constants.

Enum toString() If you print an enum, like this: System.out.println(Level.HIGH);

Then the toString() method will get called behind the scenes, so the value that will be printed out is the textual name of the enum instance. In other words, in the example above the text HIGH would have been printed.

Enum valueOf() An enum class automatically gets a static valueOf() method in the class when compiled. The valueOf() method can be used to obtain an instance of the enum class for a given String value. Here is an example: Level level = Level.valueOf(“HIGH”);

Source: tutorials.jenkov.com

Enum Fields

You can add fields to a Java enum. Thus, each constant enum value gets these fields. The field values must be supplied to the constructor of the enum when defining the constants. Here is an example: public enum Level { HIGH (3), //calls constructor with value 3 MEDIUM(2), //calls constructor with value 2 LOW (1) //calls constructor with value 1 ; // semicolon needed when fields / methods follow private final int levelCode; private Level(int levelCode) { this.levelCode = levelCode; } } Notice how the Java enum in the example above has a constructor which takes an int . The enum constructor sets the int field. When the constant enum values are defined, an int value is passed to the enum constructor.

The enum constructor must be either private or package scope (default). You cannot use public or protected constructors for a Java enum .

Enum Methods

You can add methods to a Java enum too. Here is an example: public enum Level { HIGH (3), //calls constructor with value 3 MEDIUM(2), //calls constructor with value 2 LOW (1) //calls constructor with value 1 ; // semicolon needed when fields / methods follow private final int levelCode; Level(int levelCode) { this.levelCode = levelCode; } public int getLevelCode() { return this.levelCode; } } You call a Java enum method via a reference to one of the constant values. Here is Java enum method call example: Level level = Level.HIGH; System.out.println(level.getLevelCode());

This code would print out the value 3 which is the value of the levelCode field for the enum constant HIGH .

You are not restricted to simple getter and setter methods. You can also create methods that make calculations based on the field values of the enum constant. If your fields are not declared final you can even modify the values of the fields (although that may not be so good an idea, considering that the enums are supposed to be constants).

Enum Abstract Methods

It is possible for a Java enum class to have abstract methods too. If an enum class has an abstract method, then each instance of the enum class must implement it. Here is a Java enum abstract method example: public enum Level { HIGH{ @Override public String asLowerCase() { return HIGH.toString().toLowerCase(); } }, MEDIUM{ @Override public String asLowerCase() { return MEDIUM.toString().toLowerCase(); } }, LOW{ @Override public String asLowerCase() { return LOW.toString().toLowerCase(); } }; public abstract String asLowerCase(); } Notice the abstract method declaration at the bottom of the enum class. Notice also how each enum instance (each constant) defines its own implementation of this abstract method. Using an abstract method is useful when you need a different implementation of a method for each instance of a Java enum.

Source: tutorials.jenkov.com

Enum Implementing Interface

A Java Enum can implement a Java Interface in case you feel that makes sense in your situation. Here is an example of a Java Enum implementing an interface: public enum EnumImplementingInterface implements MyInterface { FIRST(“First Value”), SECOND(“Second Value”); private String description = null; private EnumImplementingInterface(String desc){ this.description = desc; } @Override public String getDescription() { return this.description; } } It is the method getDescription() that comes from the interface MyInterface .

Implementing an interface with an Enum could be used to implement a set of different Comparator constants which can be used to sort collections of objects. Sorting of objects in Java is explained in more detail in the Java Collection Sorting Tutorial .

Source: tutorials.jenkov.com

EnumSet

Java contains a special Java Set implementation called EnumSet which can hold enums more efficiently than the standard Java Set implementations. Here is how you create an instance of an EnumSet : EnumSet enumSet = EnumSet.of(Level.HIGH, Level.MEDIUM);

Once created, you can use the EnumSet just like any other Set.

EnumMap

Java also contains a special Java Map implementation which can use Java enum instances as keys. Here is a Java EnumMap example: EnumMap<Level, String> enumMap = new EnumMap<Level, String>(Level.class); enumMap.put(Level.HIGH , “High level”); enumMap.put(Level.MEDIUM, “Medium level”); enumMap.put(Level.LOW , “Low level”); String levelValue = enumMap.get(Level.HIGH);

Enum Miscellaneous Details

Java enums extend the java.lang.Enum class implicitly, so your enum types cannot extend another class.

If a Java enum contains fields and methods, the definition of fields and methods must always come after the list of constants in the enum. Additionally, the list of enum constants must be terminated by a semicolon;

Source: tutorials.jenkov.com

Java Enum Lookup by Name or Field Without Throwing Exceptions

Source: (stubbornjava.com)

Java enumEnum lookup by name without using Enum.valueOf() by utilizing custom methods and Google’s Guava. Ignore Enum.valueOf() exception.

Outline:

  • The Enum
  • View on GitHub
  • View on GitHub
  • Better Implementations
  • View on GitHub
  • View on GitHub
  • One Step Further Indexing by Field
  • View on GitHub
  • View on GitHub
  • BONUS – Serializing an Enum as an Object with Jackson

The Enum

Using Enum.valueOf is great when you know the input is valid. However if you pass in an invalid name an exception will be thrown. In some cases this is fine. Often times we would prefer to just ignore it and return null. log.debug(“Running valueOf”); for (String name : names) { try { log.debug(“looking up {} found {}”, name, Json.serializer().toString(CardSuit.valueOf(name))); } catch (Exception ex) { log.warn(“Exception Thrown”, ex); } } 2017-02-22 14:46:38.556 [main] DEBUG c.s.examples.common.EnumLookup – Running valueOf 2017-02-22 14:46:38.804 [main] DEBUG c.s.examples.common.EnumLookup – looking up SPADE found {“displayName”:”Spade”,”symbol”:”♠”,”color”:”BLACK”} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup – looking up HEART found {“displayName”:”Heart”,”symbol”:”♥”,”color”:”RED”} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup – looking up DIAMOND found {“displayName”:”Diamond”,”symbol”:”♦”,”color”:”RED”} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup – looking up CLUB found {“displayName”:”Club”,”symbol”:”♣”,”color”:”BLACK”} 2017-02-22 14:46:38.808 [main] WARN c.s.examples.common.EnumLookup – Exception Thrown java.lang.IllegalArgumentException: No enum constant com.stubbornjava.examples.common.EnumLookup.CardSuit.Missing at java.lang.Enum.valueOf(Enum.java:238) at com.stubbornjava.examples.common.EnumLookup$CardSuit.valueOf(EnumLookup.java:1) at com.stubbornjava.examples.common.EnumLookup.main(EnumLookup.java:154)

Better Implementations

The following all work by using an index in the form of a Map. There are some minor differences as well as boilerplate concerns.

Static Map Index (Better) What is the correct data structure to use for quick lookups of fixed size? A HashMap. Now with a little extra boiler plate we have a much more efficient lookup as long as we have a good hash function. A bit more verbose, it would be nice if there was a way to reduce the boilerplate. private static final Map<String, CardSuit> nameIndex = Maps.newHashMapWithExpectedSize(CardSuit.values().length); static { for (CardSuit suit : CardSuit.values()) { nameIndex.put(suit.name(), suit); } } public static CardSuit lookupByName(String name) { return nameIndex.get(name); }

One Step Further Indexing by Field

This exact same approach can be used for additional fields of the enum. It’s not uncommon to want to look up an enum by its display name or some other property.

Static Map Indexed by Field (Better) Same approach as above but indexed on the display name instead of the enum name. private static final Map<String, CardSuit> displayNameIndex = Maps.newHashMapWithExpectedSize(CardSuit.values().length); static { for (CardSuit suit : CardSuit.values()) { displayNameIndex.put(suit.getDisplayName(), suit); } } public static CardSuit lookupByDisplayName(String name) { return displayNameIndex.get(name); }

Source: stubbornjava.com

BONUS – Serializing an Enum as an Object with Jackson

If you happened to notice our json output is a full object not just the enum name the magic comes from the Jackson annotation @JsonFormat(shape = JsonFormat.Shape.OBJECT)

Source: stubbornjava.com

Micro optimizations in Java. Good, nice and slow Enum

Source: (medium.com)

Enums are crucial part of every application larger than “Hello World“. We use them everywhere. They are actually very useful: they…

Outline:

  • Micro optimizations in Java. Good, nice and slow Enum
  • Enum.valueOf
  • Enum.values()
  • Conclusion
  • Learn more.
  • Make Medium yours.

Micro optimizations in Java. Good, nice and slow Enum

· 4 min read Enums are crucial part of every application larger than “Hello World“. We use them everywhere. They are actually very useful: they restrict the input, allow you to compare the values by the reference, provide compile-time checks, and make the code easier to read. However, using Enums has a few performance downsides. And we’ll review them in this post.

(Please consider all the code below from the point of performance) (Please do not focus on numbers, they are just examples to prove the point)

Source: medium.com

Enum.valueOf

In Blynk , one of the most popular features is called “Widget Property”. It’s when you can change the appearance of the visual widget in real-time by sending from the hardware the command like that:

Let’s take a look at existing Enum from our server:

And now look at this basic code:

Do you see what is wrong here?

Let’s rewrite the above code and create our own method based on the switch statement:

This method isn’t precisely the same, as it doesn’t throw the IllegalArgumentException in case of an unknown value. However, it’s done on purpose. Because, as you know, throwing and creating the exception (because of the stack trace) is an expensive operation.

Let’s make a benchmark:

Results (lower score means faster):

Hm… Our custom method with the switch statement is two times faster than Enum.valueOf. Something is wrong here. We need to go deeper.

As you probably know, enum classes don’t have the Java valueOf() method. The compiler generates it during the compilation. So we need to look into the byte code of the generated class to understand what is going on there:

Looks like java.lang.Enum.valueOf method is invoked inside WidgetPtoperty.valueOf method. Fortunately, this method is present in the Java code. Let’s check it:

And enumConstantDirectory:

Aha, so all we have here is a regular volatile HashMap with the enum names as the keys. And it looks like in that particular case the switch statement just outperforms the HashMap.get() method.

Let’s add valueOf with own HashMap implementation to the test as well:

Results (lower score means faster, enumMap results attached to the prev test):

Own HashMap implementation seems faster than regular Enum.valueOf() but still slower than the switch statement.

Let’s rewrite the test to have the random input:

Results (lower score means faster):

Interesting… Now, with the random input, the switch statement is 2 times slower. Looks like the difference is due to the branch prediction according to the Andrei Pangin comment. And the fastest option would be our own Map cache implementation (as it does fewer checks comparing to the Enum.valueOf).

Enum.values()

Now, let’s consider another example. It’s not so popular as the above one, but still present in many projects:

Do you see what is wrong here?

Again, Enum.values() method is generated during the compilation, so to understand what is wrong there we have to look at the byte code one more time:

You don’t need to be a byte code expert to see the .clone() method invocation. So, every time you call the Enum.values() method the array with the enum values is always copied.

The solution is pretty obvious we can cache the Enum.values() method result like that:

And use the cache field instead. Let’s check it with the benchmark:

I used the loop in that benchmark because, usually, the Enum.values() is used within the loop.

Results (lower score means faster):

The performance difference here is ~30%. That’s because the loop iteration takes some CPU as well. However, what is more important: after our fix, no allocation happens. And that’s even more important than gained speed improvement.

You may wonder, why Enum.values() is implemented in this way? Well, the explanation is quite simple. Without copy() method anyone could change the content of the returned array. And that could lead to many problems. So returning the same reference to the array with values that can be easily replaced isn’t the best idea. Immutable arrays would solve that issue, but Java doesn’t have one.

Yes, this change decreases the readability a bit and you don’t need to use it with every enum. It’s necessary only for really hot paths.

Check for example this PR for Apache Cassandra jdbc driver mssql-jdbc driver PR or this PR for http server

Conclusion

For hot paths, consider using your own Map cache of the Enum.valueOf() method. As an additional bonus, you could avoid throwing the Exception during the wrong input. That could be a game-changer for some flows

For hot paths, go with the cached Enum.values() field. This will allow you to decrease the allocation rate

Here is a source code of benchmarks, so that you can try it yourself.

Thank you for your attention, and stay tuned.

Previous post:

Micro optimizations in Java. String.equalsIgnoreCase()

Java Enum Lookup by Name or Field Without Throwing Exceptions – DZone Java

Source: (dzone.com)

There are many ways to look up Java Enums while not throwing exceptions. Some are better than others, as you’ll see while working toward boilerplate-free code.

Outline:

  • The Enum
  • The Problem
  • Better Implementations
  • One Step Further Indexing by Field
  • Bonus: Serializing an Enum as an Object With Jackson

The Enum

Here’s the enum we will be using in our examples. Let’s pick a more complex enum to also showcase looking an enum up by another field. public enum CardColor { RED, BLACK, ; } // Jackson annotation to print the enum as an Object instead of the default name. @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum CardSuit { // Unicode suits – https://en.wikipedia.org/wiki/Playing_cards_in_Unicode SPADE(“Spade”, String.valueOf((char) 0x2660), CardColor.BLACK), HEART(“Heart”, String.valueOf((char) 0x2665), CardColor.RED), DIAMOND(“Diamond”, String.valueOf((char) 0x2666), CardColor.RED), CLUB(“Club”, String.valueOf((char) 0x2663), CardColor.BLACK), ; private String displayName; private String symbol; private CardColor color; private CardSuit(String displayName, String symbol, CardColor color) { this.displayName = displayName; this.symbol = symbol; this.color = color; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public CardColor getColor() { return color; } public void setColor(CardColor color) { this.color = color; } View on GitHub .

The Problem

Using Enum.valueOf is great when you know the input is valid. However, if you pass in an invalid name, an exception will be thrown. In some cases, this is fine. Oftentimes. we would prefer to just ignore it and return null. log.debug(“Running valueOf”); for (String name : names) { try { log.debug(“looking up {} found {}”, name, Json.serializer().toString(CardSuit.valueOf(name))); } catch (Exception ex) { log.warn(“Exception Thrown”, ex); } } View on GitHub .

2017-02-22 14:46:38.556 [main] DEBUG c.s.examples.common.EnumLookup – Running valueOf 2017-02-22 14:46:38.804 [main] DEBUG c.s.examples.common.EnumLookup – looking up SPADE found {“displayName”:”Spade”,”symbol”:”♠”,”color”:”BLACK”} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup – looking up HEART found {“displayName”:”Heart”,”symbol”:”♥”,”color”:”RED”} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup – looking up DIAMOND found {“displayName”:”Diamond”,”symbol”:”♦”,”color”:”RED”} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup – looking up CLUB found {“displayName”:”Club”,”symbol”:”♣”,”color”:”BLACK”} 2017-02-22 14:46:38.808 [main] WARN c.s.examples.common.EnumLookup – Exception Thrown java.lang.IllegalArgumentException: No enum constant com.stubbornjava.examples.common.EnumLookup.CardSuit.Missing at java.lang.Enum.valueOf(Enum.java:238) at com.stubbornjava.examples.common.EnumLookup$CardSuit.valueOf(EnumLookup.java:1) at com.stubbornjava.examples.common.EnumLookup.main(EnumLookup.java:154)

Better Implementations

The following all work by using an index in the form of a Map. There are some minor differences as well as boilerplate concerns.

Static Map Index (Better) What is the correct data structure to use for quick lookups of fixed size? A HashMap. Now with a little extra boilerplate, we have a much more efficient lookup as long as we have a good hash function. A bit more verbose, and it would be nice if there was a way to reduce the boilerplate. private static final Map<String, CardSuit> nameIndex = Maps.newHashMapWithExpectedSize(CardSuit.values().length); static { for (CardSuit suit : CardSuit.values()) { nameIndex.put(suit.name(), suit); } } public static CardSuit lookupByName(String name) { return nameIndex.get(name); } View on GitHub .

2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup – Running lookupByName 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup – looking up SPADE found {“displayName”:”Spade”,”symbol”:”♠”,”color”:”BLACK”} 2017-02-22 14:46:38.810 [main] DEBUG c.s.examples.common.EnumLookup – looking up HEART found {“displayName”:”Heart”,”symbol”:”♥”,”color”:”RED”} 2017-02-22 14:46:38.810 [main] DEBUG c.s.examples.common.EnumLookup – looking up DIAMOND found {“displayName”:”Diamond”,”symbol”:”♦”,”color”:”RED”} 2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup – looking up CLUB found {“displayName”:”Club”,”symbol”:”♣”,”color”:”BLACK”} 2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup – looking up Missing found null Guava Enums.getIfPresent (Recommended) This is such a common use case that our friends over at Google made a very clean and boilerplate-free solution for us. Under the hood, it even uses WeakReferences and WeakHashMaps. Basically, this code will create a global static map keyed on the Enum’s class name and use it for lookups. public static CardSuit getIfPresent(String name) { return Enums.getIfPresent(CardSuit.class, name).orNull(); } View on GitHub .

2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup – Running Guava getIfPresent 2017-02-22 14:46:38.814 [main] DEBUG c.s.examples.common.EnumLookup – looking up SPADE found {“displayName”:”Spade”,”symbol”:”♠”,”color”:”BLACK”} 2017-02-22 14:46:38.814 [main] DEBUG c.s.examples.common.EnumLookup – looking up HEART found {“displayName”:”Heart”,”symbol”:”♥”,”color”:”RED”} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup – looking up DIAMOND found {“displayName”:”Diamond”,”symbol”:”♦”,”color”:”RED”} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup – looking up CLUB found {“displayName”:”Club”,”symbol”:”♣”,”color”:”BLACK”} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup – looking up Missing found null

One Step Further Indexing by Field

This exact same approach can be used for additional fields of the enum. It’s not uncommon to want to look up an enum by its display name or some other property.

Static Map Indexed by Field (Better) Same approach as above, but indexed on the display name instead of the enum name. private static final Map<String, CardSuit> displayNameIndex = Maps.newHashMapWithExpectedSize(CardSuit.values().length); static { for (CardSuit suit : CardSuit.values()) { displayNameIndex.put(suit.getDisplayName(), suit); } } public static CardSuit lookupByDisplayName(String name) { return displayNameIndex.get(name); } View on GitHub .

log.debug(“Running lookupByDisplayName”); for (String displayName : displayNames) { log.debug(“looking up {} found {}”, displayName, Json.serializer().toString(CardSuit.lookupByDisplayName(displayName))); } View on GitHub .

2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup – Running lookupByDisplayName 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup – looking up Spade found {“displayName”:”Spade”,”symbol”:”♠”,”color”:”BLACK”} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup – looking up Heart found {“displayName”:”Heart”,”symbol”:”♥”,”color”:”RED”} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup – looking up Diamond found {“displayName”:”Diamond”,”symbol”:”♦”,”color”:”RED”} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup – looking up Club found {“displayName”:”Club”,”symbol”:”♣”,”color”:”BLACK”} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup – looking up Missing found null Static Map Indexed by Field Utility (Better) We can’t leverage Guava here, since it would be difficult to create unique global keys for the static index. However, that doesn’t mean we can’t make our own helpers! public class EnumUtils { public static <T, E extends Enum> Function<T, E> lookupMap(Class clazz, Function<E, T> mapper) { @SuppressWarnings(“unchecked”) E[] emptyArray = (E[]) Array.newInstance(clazz, 0); return lookupMap(EnumSet.allOf(clazz).toArray(emptyArray), mapper); } public static <T, E extends Enum> Function<T, E> lookupMap(E[] values, Function<E, T> mapper) { Map<T, E> index = Maps.newHashMapWithExpectedSize(values.length); for (E value : values) { index.put(mapper.apply(value), value); } return (T key) -> index.get(key); } } View on GitHub .

Now we have a fairly boilerplate-free generic solution. private static final Function<String, CardSuit> func = EnumUtils.lookupMap(CardSuit.class, e -> e.getDisplayName()); public static CardSuit lookupByDisplayNameUtil(String name) { return func.apply(name); } View on GitHub .

log.debug(“Running lookupByDisplayNameUtil”); for (String displayName : displayNames) { log.debug(“looking up {} found {}”, displayName, Json.serializer().toString(CardSuit.lookupByDisplayNameUtil(displayName))); } View on GitHub .

Source: dzone.com

Bonus: Serializing an Enum as an Object With Jackson

If you happened to notice, our JSON output is a full object, not just the enum name. The magic comes from the Jackson annotation @JsonFormat(shape = JsonFormat.Shape.OBJECT)

Source: dzone.com

How to get an enum value from a String in Java?

Source: (frontbackend.com)

1. Introduction An enum is a special class in Java that represents a group of constants. In this short tutorial, we are going to present how to get en…

Outline:

  • 1. Introduction
  • 2. The problem : Get enum using String value

1. Introduction

An enum is a special class in Java that represents a group of constants. In this short tutorial, we are going to present how to get enum value using String.

2. The problem : Get enum using String value

public enum Alphabet { A , B , C , D , E , F , G } We want to find the enum value of a String, for example, “A” which would be Alphabet.A .

Source: frontbackend.com