加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:26:45 所属栏目:Java 来源:网络整理
导读:我有几个 Java枚举,看起来像下面(为保密等编辑). 在每种情况下,我有一个我真的不满意的查找方法;在下面的例子中,它是findByChannelCode. public enum PresentationChannel { ChannelA("A"),ChannelB("B"),ChannelC("C"),ChannelD("D"),ChannelE("E"); privat
我有几个 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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读