首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问数组的Enum

如何访问数组的Enum
EN

Stack Overflow用户
提问于 2019-05-03 13:33:58
回答 2查看 93关注 0票数 2

我有两套产品

代码语言:javascript
复制
public enum ProductType {

    FOUNDATION_OR_PAYMENT ("946", "949", "966"),
    NOVA_L_S_OR_SESAM ("907", "222");

    private String[] type;

    ProductType(String... type) {
        this.type = type;
    }
}

然后给出一个值“actualProductType”,我需要检查它是否是productType ..How的一部分,我要这样做吗..

代码语言:javascript
复制
isAnyProductTypes(requestData.getProductType(), ProductType.NOVA_L_S_SESAM)
代码语言:javascript
复制
 public boolean isAnyProductTypes(String actualProductType, ProductType productTypes) {
        return Arrays.stream(productTypes).anyMatch(productType -> productType.equals(actualProductType));
    }

我在这部分( Arrays.stream(productTypes) )有一个错误。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-03 13:41:29

由于枚举没有改变,您可以在其中构建一个Map,以便更快地查找:

代码语言:javascript
复制
public enum ProductType {


    FOUNDATION_OR_PAYMENT("946", "949", "966"),
    NOVA_L_S_OR_SESAM("907", "222");

    static Map<String, ProductType> MAP;

    static {
        MAP = Arrays.stream(ProductType.values())
                    .flatMap(x -> Arrays.stream(x.type)
                                        .map(y -> new SimpleEntry<>(x, y)))
                    .collect(Collectors.toMap(Entry::getValue, Entry::getKey));
    }

    private String[] type;

    ProductType(String... type) {
        this.type = type;
    }

    public boolean isAnyProductTypes(String actualProductType, ProductType productTypes) {
        return Optional.ofNullable(MAP.get(actualProductType))
                       .map(productTypes::equals)
                       .orElse(false);
    }
}
票数 2
EN

Stack Overflow用户

发布于 2019-05-03 13:50:14

您应该将类型更改为Set<String>和构造函数。

代码语言:javascript
复制
ProductType(String... type) {
    this.type = new HashSet<>(Arrays.asList(type));
}

而且查找将非常简单

代码语言:javascript
复制
return productType.getType().contains(requestData.getProductType())
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55970915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档