Reputation: 75127
I have an enum like that:
public enum Lang {
TR("tr"),
EN("en"),
SE("se");
private String langName;
private Lang(String langName) {
this.langName = langName;
}
}
at another class I want to check whether a langName exists or not. If I put a getter method I can iterate over langNames:
for (Lang langEnum : Lang.values()) {
langEnum.getLangName();
}
However my enum may be too long and I don't want to iterate over an array. I want to use a Map or Set. On the other hand I don't want to another variable within my enum.
How can I check whether my enum has a langName or not?
Upvotes: 2
Views: 121
Reputation: 78579
Well, if every enum constant represents a language (as the code seems to suggest), then I would use an EnumSet.
Set<Lang> langs = EnumSet.allOf(Lang.class);
And then I can check if a language is already there. Like
if(langs.contains(Lang.EN) {
//...
}
Not sure if this is the answer you were looking for. The contains method of EnumSet would not even iterate over the internal collection. The internal collection would be stored in an array and finding an element is calculated based on a hash. So, this in fact, should achieve what you requested in the question.
Upvotes: 3
Reputation: 396
How about using valueOf
?
Lang lang = null;
try {
lang = Lang.valueOf(enumName);
// enum exists
} catch (IllegalArgumentException e) {
// enum does not exist
}
Since your enum name is just the language name capitalized, you can just capitalize the language name and pass it into valueOf
.
Upvotes: 1