java - 使用 Google Guava 进行 getIfPresent() 按枚举值进行搜索

标签 java enums guava

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/

相关文章:

C++11 枚举类 : plus int failed to compile, 为什么?

java - 在嵌套循环中将子列表添加到 Guava 表中会出现并发修改错误

java - 如何使用 Google Guava 创建具有不可变键且无重复项的 map ?

java - 使用 RMI 缓存复制器时出现 EhCache 死锁问题

delphi - 如何遍历任何给定集合中的枚举?

java - JPanel 显示为一个小白框

c++ - 以编程方式独立于其元素的值推断枚举的大小?

java - 能否通过Guava库提供的Maps.filteKey/Value方法实现类似数据库的Limit功能

java - 由于包结构导致的 EclipseLink MOXy 异常

java - 如何将不同时区的日期字符串转换为一个时区中的日期对象