【问题标题】:Get a string in a whole enum and return the enum constant获取整个枚举中的字符串并返回枚举常量
【发布时间】:2017-03-25 16:46:23
【问题描述】:

我创建了一个带有一些字符串作为属性的常量的枚举。每个常量中字符串的数量不同,所以我使用了可变参数(我第一次这样做)。这是我的枚举:

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;
    }
};

现在我希望能够输入如下内容:

CursorInfo.getCursor("Bait");

然后我希望它返回:“FISH”或序数(我不介意它返回什么),即:“4”。 我问过某人,他说我应该将其添加到枚举中:

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();
    }

但我不知道如何使用它,也不知道它是否有效。 简而言之:当我使用其中一个字符串作为参数时,如何返回枚举常量 id/name?

【问题讨论】:

  • 如果我关注该帖子并将其更改为我的需要,我会看看我是否可以让它工作,谢谢!
  • 改用地图,并在使用时退出 RSPS。
  • @JacobG。 “退出 RSPS”是什么意思?
  • 哈哈哈,我为什么要退出RSPS? Andreas 它的意思是“RuneScape 私人服务器”。

标签: java enums


【解决方案1】:

希望以下截图对你有所帮助。当然,您可以使用 Stream API 来简化它。但是概念应该很清楚。

只需将其添加到您的枚举声明中即可。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多