【问题标题】:How to access Enum of arrays如何访问数组的枚举
【发布时间】:2019-05-03 13:33:58
【问题描述】:

我有两套产品

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的一部分..我该怎么做..

isAnyProductTypes(requestData.getProductType(), ProductType.NOVA_L_S_SESAM)

 public boolean isAnyProductTypes(String actualProductType, ProductType productTypes) {
        return Arrays.stream(productTypes).anyMatch(productType -> productType.equals(actualProductType));
    }

我在这部分 Arrays.stream(productTypes) 收到错误

【问题讨论】:

  • 这里的术语有些不对劲。产品类型是字符串还是字符串数组?它们不能都是“产品类型”

标签: java enums java-8 java-stream


【解决方案1】:

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

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】:

    您应该将类​​型更改为Set&lt;String&gt; 和构造函数

    ProductType(String... type) {
        this.type = new HashSet<>(Arrays.asList(type));
    }
    

    而且查找会非常简单

    return productType.getType().contains(requestData.getProductType())
    

    【讨论】:

    • 并不是我想说的问题。这会改变用户共享的预期 api 的合同。
    • @Naman 它解决了这个问题。 OP 没有说他不能修改枚举,这肯定比每次都进行查找要好,这是最简单的解决方案......真的不需要流
    • String[] 存储为Set&lt;String&gt; 并不能解决问题,这是我想指出的。它只是每种类型的附加属性。要检查任何类型都没有值,您仍然必须遍历所有此类类型并检查其中是否包含值。
    • @Naman 如果您查看isAnyProductTypes 签名,您会看到它收到一个ProductType,所以他想在给定的枚举值中搜索而不是全部
    • 好吧,我想说这个问题在这方面还不清楚,然后对于类型,productTypes 它读取..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多