gpt4 book ai didi

java - 验证枚举结构中的值

转载 作者:行者123 更新时间:2023-12-02 10:02:57 24 4
gpt4 key购买 nike

我使用此 JUnit 测试来从数据库加载值并将其保存回来。到目前为止,这是当前的实现:

public class BitStringTest {

Map<FeatureBitString, Boolean> features = new HashMap<>();

public void enableFeature(FeatureBitString feature) {
features.put(feature, true);
}

public void disableFeature(FeatureBitString feature) {
features.put(feature, false);
}

public boolean isFeatureEnabled(FeatureBitString feature) {
Boolean enabled = features.get(feature);
return enabled != null && enabled;
}

public String convertToDatabaseValue() {
return Arrays.stream(FeatureBitString.values()).map(f -> isFeatureEnabled(f) ? "1" : "0").collect(joining());
}

public Map<FeatureBitString, Boolean> initFromDatabaseValue(String bitString) {
// Note that, bitString length should equals to your number of feature. Or you
// have to padding it
char[] bitArray = bitString.toCharArray();
return Arrays.stream(FeatureBitString.values())
.collect(toMap(f -> f, f -> bitArray[f.getIndex()] == '1', (v1, v2) -> v2, LinkedHashMap::new));
}

@Test
public void testToDatabaseValue() {
System.out.println("\nProducing Features ");
features.put(FeatureBitString.A, true);
features.put(FeatureBitString.F, true);
Assertions.assertEquals(convertToDatabaseValue(), "1000010");
}
}

enum FeatureBitString {
A("Type1", 0), // index 0 in bit string
B("Type2", 1), // index 1 in bit String
C("Type3", 2), // index 2 in bit String
D("Type3", 3), // index 3 in bit String
E("Type4", 4), // index 4 in bit String
F("Type5", 5), // index 5 in bit String
G("Type6", 6); // index 6 in bit String

private final String featureName;
private final int index;

private FeatureBitString(String featureName, int value) {
this.featureName = featureName;
this.index = value;
}

public String getFeatureName() {
return featureName;
}

public int getIndex() {
return index;
}
}

我如何验证枚举FeatureBitString中是否存在值“Type2”?在加载之前,我想检查该值是否根据枚举数据存在。

最佳答案

public static Optional<FeatureBitString> getByFeatureName(String featureName) {
return Optional.of(values()).map(FeatureBitString::getFeatureName).filter(f -> f.equals(featureName)).findAny();
}

if (FeatureBitString.getByFeatureName("Type2").isPresent()) { // ...

关于java - 验证枚举结构中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55499018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com