public enum Dictionary {PLACEHOLDER1 ("To be updated...", "Placeholder", "adjective"),PLACEHOLDER2 ("To be updated...", "Placeholder", "adverb"),PLACEHOLDER3 ("To be updated...", "Placeholder", "conjunction");private String definition;private String name;private String partOfSpeech;private Dictionary (String definition, String name, String partOfSpeech) { this.definition = definition; this.name = name; this.partOfSpeech = partOfSpeech; }public String getName() { return name;}public class DictionaryUser { public static Dictionary getIfPresent(String name) { return Enums.getIfPresent(Dictionary.class, name).orNull(); } *public static Dictionary getIfPresent(String name) { return Enums.getIfPresent(Dictionary.class, name.getName()).orNull(); }我最近剛剛遇到 getIfPresent() 基本上有一個全局靜態映射鍵在 Enum 類名上進行查找。我遇到的問題是,我想使用我的 getter getName() 進行查找,而不是使用枚舉名稱的名稱。在我提供的示例中,如果用戶輸入占位符,所有三個值都會顯示出來。這可以通過我的方法實現嗎?我在不起作用的方法旁邊放了一個 *。
1 回答

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
由于您需要所有匹配的對象,但Enums.getIfPresent只會給您一個對象,因此您可以通過執行以下操作輕松實現目標:
public static Dictionary[] getIfPresent(String name)
{
List<Dictionary> response = new ArrayList<>( );
for(Dictionary d : Dictionary.values())
{
if( d.getName().equalsIgnoreCase( name ) )
{
response.add(d);
}
}
return response.size() > 0 ? response.toArray( new Dictionary[response.size()] ) : null;
}
添加回答
舉報
0/150
提交
取消