使用 Google Guava 的 getIfPresent() 按枚举值搜索
Using Google Guava for getIfPresent() to search by values of enum
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() 基本上有一个全局静态映射键控在枚举 class 名称上进行查找。相反,我遇到的问题是,我想利用我的 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;
}
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() 基本上有一个全局静态映射键控在枚举 class 名称上进行查找。相反,我遇到的问题是,我想利用我的 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;
}