java – 通过值查找枚举的正确方法
|
我有几个
Java枚举,看起来像下面(为保密等编辑).
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);
}
解决方法
完全可能没有这样做. 虽然哈希表提供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); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
