查找与String数组中的值关联的枚举类型

时间:2017-09-17 18:08:05

标签: java android enums

我有一个包含String和2个String数组作为参数的枚举。

     public enum MedicalInformationTypeEnm {

    foodAllergies("Food Allergies",
            new String[]{},
            new String[]{
            "Milk", "Cheese", "Curd", "Tamarind", "Nuts", "Garlic", "Peanut",
            "Soya", "Lemon", "Other Fruits", "Wheat", "Oats", "Peppers", "Gluten",
            "Egg", "Meat", "Shellfish/Fish", "Synthetic Colouring", "Preserved Foods"}),

    drugAllergies("Drug Allergies",
            new String[]{"Oral Contraceptives","Sulfa Drugs"},
            new String[]{
            "Antibiotics","Painkillers","NSAIDS","Sedatives","Psychiatric Drugs",
            "Local Anaesthetics (Xylocaine, Lignocaine)","Cardiovascular Drugs",
            "Vaccines","Phenytoin(Eptoin)","Carbamazepine(Tegretol)","Penicillin","Contrast Dyes"});

}

如何获得与之相关的枚举,例如" Garlic"在food Allergies?

2 个答案:

答案 0 :(得分:1)

你走了,

public enum MedicalInformationTypeEnm {

    foodAllergies("Food Allergies",
        new String[]{},
        new String[]{
                "Milk", "Cheese", "Curd", "Tamarind", "Nuts", "Garlic", "Peanut",
                "Soya", "Lemon", "Other Fruits", "Wheat", "Oats", "Peppers", "Gluten",
                "Egg", "Meat", "Shellfish/Fish", "Synthetic Colouring", "Preserved Foods"}),

    drugAllergies("Drug Allergies",
        new String[]{"Oral Contraceptives", "Sulfa Drugs"},
        new String[]{
                "Antibiotics", "Painkillers", "NSAIDS", "Sedatives", "Psychiatric Drugs",
                "Local Anaesthetics (Xylocaine, Lignocaine)", "Cardiovascular Drugs",
                "Vaccines", "Phenytoin(Eptoin)", "Carbamazepine(Tegretol)", "Penicillin", "Contrast Dyes"});


    private String name;
    private String[] drug;
    private String[] allergies;

    MedicalInformationTypeEnm(String name, String[] drug, String[] allergies) {
        this.name = name;
        this.drug = drug;
        this.allergies = allergies;
    }

    public static MedicalInformationTypeEnm fromAllergy(String allergy) {

        for (MedicalInformationTypeEnm info : values()) {
            for (String a : info.allergies) {
                if (a.equalsIgnoreCase(allergy)) {
                    return info;
                }
            }
        }

        throw new IllegalArgumentException("Allergy not found!");
    }


    public static void main(String[] args) {
        MedicalInformationTypeEnm info =
            MedicalInformationTypeEnm.fromAllergy("Garlic");
        System.out.println(info);

        info = MedicalInformationTypeEnm.fromAllergy("Penicillin");
        System.out.println(info);

        info = MedicalInformationTypeEnm.fromAllergy("test");
        System.out.println(info);
    }
}

答案 1 :(得分:0)

您可以使用

循环访问枚举
.values()

然后循环遍历数组,直到找到“Garlic”。