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() 进行查找,而不是通过枚举名称的名称。在我提供的示例中,如果用户输入占位符,所有三个值都会显示。我的方法可以实现吗?我在不起作用的方法旁边加了 *。
最佳答案
由于您需要所有匹配的对象,但 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;
}
关于java - 使用 Google Guava 进行 getIfPresent() 按枚举值进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818395/