Suppose I have the enum below:
public enum RockPaperScissors {
R("Rock"),
P("Paper"),
S("Scissors");
private final String fullName;
RockPaperScissors(String fullName) {
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
public static RockPaperScissors getInstanceByFullName(String fullName) {
return Arrays.stream(values())
.filter(value -> value.getFullName().equals(fullName))
.findFirst().orElseThrow(() -> new IllegalArgumentException("No such value in the enum"));
}
}
I want both
RockPaperScissors.valueOf("R") and
RockPaperScissors.getInstanceByFullName("Paper") to work because I call them by different data providers.
Is there any better alternative to the getInstanceByFullName method that I have written?
Edit: My question was whether the Java enum API provides some alternative methods, which apparently it does not. As ernest_k suggested, I improved the getInstanceByFullName method.
The simplest solution would probably be to maintain a static Map<String, RockPaperScissors> in the enum:
public enum RockPaperScissors {
R ("Rock"),
P ("Paper"),
S ("Scissors");
private static final Map<String, RockPaperScissors> byFullName = new HashMap<>();
private final String fullName;
RockPaperScissors(String fullName) {
this.fullName = fullName;
byFullName.put(fullName, this);
}
public String getFullName() {
return fullName;
}
public static RockPaperScissors getInstanceByFullName(String fullName) {
return byFullName.get(fullName);
}
}
Essentially, you just precompute a Map as the enum class is loaded to allow for quick lookups by the full names.
(Whether or not it's actually faster than looping over all the values depends on the size of the enum, though. With just three elements, looping might very well be faster.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With