使用Google Guava for getIfPresent()按枚举值搜索

问题描述 投票:0回答:1
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()进行查找,而不是使用Enum名称的名称。在我提供的示例中,如果用户键入占位符,则会显示所有三个值。这可以通过我的方法实现吗?我在我的方法旁边放了一个不起作用的*。

java enums guava
1个回答
0
投票

由于你需要所有匹配的对象,但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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.