How to access Enum of arrays

Jenny :

I have two sets of Products

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;
    }
}

Then given a value"actualProductType" I need to check if it is part of the productType ..How do I do this ..

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

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

I get an error at this part Arrays.stream(productTypes)

Eugene :

Since your enum does not change, you could build a Map inside it for faster look-up:

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);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97289&siteId=1