Ho diverse enumerazioni Java simili a quelle riportate di seguito (modificate per riservatezza, ecc.). In ogni caso, ho un metodo di ricerca che non sono davvero soddisfatto; nell'esempio seguente, è findByChannelCode
.Il modo corretto per cercare un enum in base al valore
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;
}
}
Il problema è, mi sento stupida a fare queste ricerche lineari quando ho potuto solo utilizzare un HashMap<String, PresentationChannel>
. Così ho pensato alla soluzione qui sotto, ma è un po 'più disordinata che mi piacerebbe sperare e, più precisamente, non mi importava di re-inventare la ruota quando sicuramente qualcun altro ha scoperto questo. Volevo ottenere un po 'del saggio saggio di questo gruppo: qual è il modo corretto di indicizzare un enum in base al valore?
La mia soluzione:
ImmutableMap<String, PresentationChannel> enumMap = Maps.uniqueIndex(ImmutableList.copyOf(PresentationChannel.values()), new Function<PresentationChannel, String>() {
public String apply(PresentationChannel input) {
return input.getChannelCode();
}});
e, nel enum:
public static PresentationChannel findByChannelCode(String channelCode) {
return enumMap.get(channelCode);
}
si capisce che le mappe enum-> EnumMap non oggetto viceversa? – bestsss
Il profiling del codice mostra che la ricerca lineare è inadeguata? – trashgod
@bestsss, forse la mia mappa è mal chiamata. Non è un EnumMap, solo una mappa da String-> PresentationChannel (vale a dire-> istanza) – Ray