2017-03-25 174 views
0

我已经做了一个枚举常量,有一些字符串作为属性。字符串的数量在每个常量中是不同的,所以我使用了可变参数(第一次我这样做)。这是我的枚举:获取整个枚举中的字符串,并返回枚举常量

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"); 

,然后我想这回:“鱼”或序(我不介意它返回的),即:“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?

+2

的可能重复http://stackoverflow.com/questions/11047756/getting-enum-associated-with-int-value –

+0

我去看看,如果我能得到它,如果我遵循岗位工作,将其更改为我的需要,谢谢! – xX4m4zingXx

+0

改为使用地图,然后退出RSPS。 –

回答

1

我希望以下Snipped可以帮助你。当然,您可以使用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; 
} 
+0

谢谢,这个作品。 – xX4m4zingXx