【发布时间】:2021-02-18 17:45:42
【问题描述】:
我正在尝试创建一个值为 1,-1,0 的枚举,但在映射数据时,-1 的未知序数值即将到来。下面是 enum 的一段代码。如何使用枚举来检索 -1 的序数值
@RequiredArgsConstructor
public enum Number {
MULTIPLE(0, -1, "MULTIPLE"),
ZERO(1, 0, "ZERO"),
ONE(2, 1, "ONE");
private static final Map<Integer, Number> DOCUMENT_CARDINALITY_ID = Arrays.stream(values())
.collect(Collectors.toMap(Number :: intValue, Function.identity()));
private static final Map<String, Number> DOCUMENT_CARDINALITY_BY_CODE = Arrays.stream(values())
.collect(Collectors.toMap(Number :: toString, Function.identity()));
private final int value;
private final int id;
private final String code;
public static Number of(int id) {
isTrue(DOCUMENT_CARDINALITY_ID.containsKey(id), "the id " + id + " is not valid!");
return DOCUMENT_CARDINALITY_ID.get(id);
}
public static Number of(String code) {
notNull(code, "the code is null!");
isTrue(DOCUMENT_CARDINALITY_BY_CODE.containsKey(code), "the code " + code + " is not valid!");
return DOCUMENT_CARDINALITY_BY_CODE.get(code);
}
public int intValue() {
if (id == -1) {
return 0;
} else if (id == 0) {
return 1;
} else {
return 2;
}
}
@Override
public String toString() {
return code;
}
}
【问题讨论】:
标签: java spring spring-boot hibernate spring-mvc