Reputation: 941
I've made an enum with constants that have some strings as properties. The amount of strings is different in each constant, so I used varargs (first time I did this). This is my enum:
enum CursorInfo {
NORMAL("Walk-to"),
TAKE("Take"),
USE("Use"),
TALK("Talk-to"),
FISH("Net", "Bait", "Cage", "Harpo");
String[] toolTip;
CursorInfo(String... toolTip) {
this.toolTip = toolTip;
}
};
Now I want to be able to type something like:
CursorInfo.getCursor("Bait");
and then I want this to return: "FISH" or the ordinal(I don't mind what it returns), which is: "4". I asked someone about this and he said I should add this to the enum:
private static final Set<CursorInfo> SET = EnumSet.allOf(CursorInfo.class);
public static Optional<CursorInfo> getCursor(String toolTip) {
return SET.stream().filter(info -> Arrays.stream(info.toolTip).anyMatch(option -> option.contains(toolTip))).findAny();
}
But I have no idea how to use this and if this even works. In short: How can I return the enum constants id/name, when I'm using one of the strings as an argument?
Upvotes: 0
Views: 99
Reputation:
I hope the following Snipped helps you. Of course your can simplify it with the use of the Stream API. But the concept should be clear.
Just add this to your enum declaration.
public static CursorInfo getCursor(String search)
{
for(CursorInfo cursorValue : CursorInfo.values())
{
for(String tool : cursorValue.toolTip)
{
if (search.equals(tool))
return cursorValue;
}
}
//proper error handling
return null;
}
Upvotes: 1