java – 通过值查找枚举的正确方法

我有几个 Java枚举,看起来像下面(为保密等编辑).
在每种情况下,我有一个我真的不满意的查找方法;在下面的例子中,它是findByChannelCode.
public enum PresentationChannel {
    ChannelA("A"),ChannelB("B"),ChannelC("C"),ChannelD("D"),ChannelE("E");

    private String channelCode;

    PresentationChannel(String channelCode) {
        this.channelCode = channelCode;
    }

    public String getChannelCode() {
        return this.channelCode;
    }

    public PresentationChannel findByChannelCode(String channelCode) {
        if (channelCode != null) {
            for (PresentationChannel presentationChannel : PresentationChannel.values()) {
                if (channelCode.equals(presentationChannel.getChannelCode())) {
                    return presentationChannel;
                }
            }
        }

        return null;
    }
}

问题是,当我可以使用HashMap< String,PresentationChannel>时,我觉得这些线性查找很愚蠢.所以我想到了下面的解决方案,但是我希望有点乱七八糟,更重要的是,当有人遇到这个问题的时候,我并不在乎重新发明轮子.我想要得到这个组的一些圣人智慧:按价值指数枚举的正确方式是什么?

我的解决方

ImmutableMap<String,PresentationChannel> enumMap = Maps.uniqueIndex(ImmutableList.copyOf(PresentationChannel.values()),new Function<PresentationChannel,String>() {
        public String apply(PresentationChannel input) {
            return input.getChannelCode();
        }});

并在枚举中:

public static PresentationChannel findByChannelCode(String channelCode) {
     return enumMap.get(channelCode);
}

解决方法

I wanted to get some of the sage wisdom of this group: what is the proper way to index an enum by value?

完全可能没有这样做.

虽然哈希表提供O(1)查找,但它们也具有相当大的常量开销(用于哈希计算等),因此对于小集合,线性搜索可能会更快(如果“有效方式”是“定义”办法”).

如果你只是想要一种DRY的方法来做,那么我假设Guava的Iterables.find是另一种选择:

return channelCode == null ? null : Iterables.find(Arrays.asList(values()),new Predicate<PresentationChannel>() {
        public boolean apply(PresentationChannel input) {
            return input.getChannelCode().equals(channelCode);
        }
    },null);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...