In Enum
class, how to get the name of the Enum
object using one of its field values.
public enum Example {
Object1("val1", "val2"),
Object2("val3", "val4");
}
I have the val1
with me. Can I get Object1
using it ?
In Enum
class, how to get the name of the Enum
object using one of its field values.
public enum Example {
Object1("val1", "val2"),
Object2("val3", "val4");
}
I have the val1
with me. Can I get Object1
using it ?
You didn't actually show anything that those strings correspond to, so I'll assume you have fields named foo
and bar
:
public enum Example {
final String foo;
final String bar;
private Example(String foo, String bar) {
this.foo = foo;
this.bar = bar;
}
}
In order to look up by foo
, you'll just need some method that looks for a match:
public static Example ofFoo(String foo) {
for(Example e : Example.values()) {
if(e.foo.equals(foo))
return e;
}
return null;
}
As long as you don't have a crazy number of enum values, this will generally be fine. If performance is actually an issue, you can cache Example.values()
in a private static array or even set up something like a Guava ImmutableMap<String,Example>
.
Your enum
would look as follows:
public enum Example {
Object1("val1", "val2"),
Object2("val3", "val4");
String str1;
String str2;
Example(String str1, String str2){
this.str1 = str1;
this.str2 = str2;
}
static Example getEnumByStr1(String str1){
for (Example e : values())
if (e.str1.equals(str1))
return e;
return null;
}
}
You can get the enum by string value then like that:
Example.getNameByStr1("val1");
You can do it in following way with O(1)
complexity if you can assure that every Enum
constant will have unique first value. We have to create inner class to manage map of val1
and Example
because Enum
will not allow us to add value in static map inside the constructor.
public enum Example {
Object1("val1", "val2"), Object2("val3", "val4");
private static final class ExampleValManager {
static final Map<String, Example> EXAMPLE_VAL_MANAGER_MAP = new HashMap<>();
}
private String val1;
private String val2;
private Example(String val1, String val2) {
this.val1 = val1;
this.val2 = val2;
ExampleValManager.EXAMPLE_VAL_MANAGER_MAP.put(val1, this);
}
public static Example getExampleByVal1(String val) {
return ExampleValManager.EXAMPLE_VAL_MANAGER_MAP.get(val);
}
}
Use it in following way,
public class Test {
public static void main(String[] args) {
System.out.println(Example.getExampleByVal1("val1"));
}
}
OUTPUT
Object1