我有以下枚举
public enum ApiGroup {
H("gp"),
S_CARDS("cards"),
S_CARDMETADATA("cardmetadata"),
S_PRODUCTS("products");
private String value;
private ApiGroupType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
private static final List<String> sApiGroups = Arrays
.asList(ApiGroupType.S_CARDS.value, ApiGroupType.S_CARDMETADATA.value, ApiGroupType.S_PRODUCTS.value );
public static List<String> getSApiGroupsList() {
return sApiGroups;
}
目前,我正在通过创建列表来获取所需的值。如果将来需要向列表中添加任何内容,则需要首先将所需的值添加为枚举,然后在列表中是否有更好的方法可以避免在 2 个位置进行这种添加。通过在单个地方增加值(value)应该可行。
最佳答案
将方法更改为以下内容并删除 sApiGroups
静态列表。
public static List<String> getSApiGroupsList() {
return Arrays.stream(values())
.filter(apiGroup -> apiGroup.name().startsWith("S_"))
.map(ApiGroup::getValue)
.collect(Collectors.toList());
}
了解有关 docs 中的 values()
方法的更多信息.
编辑
根据 @ernest_k的评论,我们不需要流为此方法的每次调用。所以可以有:
private static final List<String> sApiGroups = Arrays.stream(values())
.filter(apiGroup -> apiGroup.name().startsWith("S_"))
.map(ApiGroup::getValue)
.collect(Collectors.toList());
public static List<String> getSApiGroupsList() {
return sApiGroups;
}
关于java - 单个枚举中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60501311/