我有几个
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 enumMap = Maps.uniqueIndex(ImmutableList.copyOf(PresentationChannel.values()),new Function() {
public String apply(PresentationChannel input) {
return input.getChannelCode();
}});
并在枚举中:
public static PresentationChannel findByChannelCode(String channelCode) {
return enumMap.get(channelCode);
}