枚举反转
第一种 使用Guava的Maps实现
private static final Map<Integer, JobWeekEnum> LOOKUP = Maps.uniqueIndex(
Arrays.asList(JobWeekEnum.values()),JobWeekEnum::getCnWeek
);
@Nullable
public static JobWeekEnum reversal(int cnWeek) {
return LOOKUP.get(cnWeek);
}
public static Integer resolve(String desc) {
AttrSourceEnum by = EnumUtil.getBy(AttrSourceEnum.class, key -> key.getDesc().equals(desc));
if (by == null) {
return null;
}
return by.getCode();
}
第三种使用循环
public static String resolve(Integer code) {
for (DeviceStatusEnum deviceStatusEnum : DeviceStatusEnum.values()) {
if (deviceStatusEnum.getCode().equals(code)){
return deviceStatusEnum.getDesc();
}
}
return null;
}
第四种使用Map
private static Map<Integer, PizzaStatus> timeToDeliveryToEnumValuesMapping = new HashMap<>();
static {
for (PizzaStatus pizzaStatus : PizzaStatus.values()) {
timeToDeliveryToEnumValuesMapping.put(
pizzaStatus.getTimeToDelivery(),
pizzaStatus
);
}
}
第五种使用Stream
Optional<PizzaStatus> pizzaStatus = Arrays.stream(PizzaStatus.values())
.filter(p -> p.getTimeToDelivery() == timeToDeliveryForOrderedPizzaStatus)
.findFirst();
assertThat(pizzaStatus).hasValue(PizzaStatus.ORDERED);