简体   繁体   English

使用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();
    }

I just recently came across getIfPresent() to basically have a global static map keyed on the Enum class name for lookup. 我最近刚遇到getIfPresent(),基本上有一个全局静态映射键入Enum类名称进行查找。 The problem I have is instead, I would like to utilized my getter getName() for the lookup instead of by the name of the Enum name. 我遇到的问题是,我想利用我的getter getName()进行查找,而不是使用Enum名称的名称。 In the example I have provided if the user typed in placeholder, all three values will show up. 在我提供的示例中,如果用户键入占位符,则将显示所有三个值。 Is this achievable with my approach? 用我的方法可以做到吗? I put a * next to my approach that does not work. 我在无法使用的方法旁边加了*。

Since you need all matching objects but Enums.getIfPresent will give you only one object, you can easily achieve your goal by doing this : 由于您需要所有匹配的对象,但是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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM