Search code examples
javaenumsguava

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. 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. 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.


Solution

  • Since you need all matching objects but Enums.getIfPresent will give you only one object, you can easily achieve your goal by doing this :

        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;
        }