how to use enumUtils in java

www.laut‮irut‬.com
how to use enumUtils in java

EnumUtils is a utility class provided by the Apache Commons Lang library that provides utility methods for working with enum types in Java. To use the EnumUtils class in your Java project, you need to include the Apache Commons Lang library in your classpath.

Here are some examples of how you can use the EnumUtils class in Java:

  1. To get the enum constant with a specified name, you can use the EnumUtils.getEnum method. This method returns the enum constant with the specified name, or null if no such constant exists.
EnumUtils.getEnum(MyEnum.class, "VALUE_A"); // Returns the MyEnum.VALUE_A constant
EnumUtils.getEnum(MyEnum.class, "VALUE_B"); // Returns the MyEnum.VALUE_B constant
EnumUtils.getEnum(MyEnum.class, "VALUE_C"); // Returns null
  1. To get the enum constants as a List, you can use the EnumUtils.getEnumList method. This method returns a List containing all the enum constants in the specified enum type.
List<MyEnum> values = EnumUtils.getEnumList(MyEnum.class); // Returns a list containing all the MyEnum constants
  1. To get the enum constants as an array, you can use the EnumUtils.getEnum method. This method returns an array containing all the enum constants in the specified enum type.
MyEnum[] values = EnumUtils.getEnum(MyEnum.class); // Returns an array containing all the MyEnum constants
  1. To get the enum constant with the maximum value of a specified field, you can use the EnumUtils.max method. This method returns the enum constant with the maximum value of the specified field, or null if no such constant exists.
EnumUtils.max(MyEnum.class, (e1, e2) -> Integer.compare(e1.getValue(), e2.getValue())); // Returns the MyEnum constant with the maximum value

These are just a few examples of how you can use the EnumUtils class to work with enum types in Java. The EnumUtils class provides many other utility methods that you can use for various operations on enum types, such as getting the enum constants as a Set or a Map, or finding the enum constants that match a specific predicate.

Note that the EnumUtils class is a utility class and cannot be instantiated. All of its methods are static, so you do not need to create an instance of the EnumUtils class to use them.

Created Time:2017-11-01 22:29:47  Author:lautturi