gpt4 book ai didi

java - 使用最合适的数据结构简化嵌套的 if-else 结构

转载 作者:行者123 更新时间:2023-12-04 07:28:23 25 4
gpt4 key购买 nike

我有一个嵌套的 if-else 块,其中存在一系列需要以特定顺序执行的条件。下面是代码示例。

        Map<String, String> DataHashMap = new HashMap<>();
String SPECIES = "SPECIES";
String NATIONALITY = "NATIONALITY";
String STATE = "STATE";
String GENDER = "GENDER";
String OCCUPATION = "OCCUPATION";
String HUMAN = "HUMAN";
String AMERICAN = "AMERICAN";
String WASHINGTON = "WASHINGTON";
String FEMALE = "FEMALE";
String BANKER = "BANKER";

DataHashMap.put(SPECIES, HUMAN);
DataHashMap.put(NATIONALITY, AMERICAN);
DataHashMap.put(STATE, WASHINGTON);
DataHashMap.put(GENDER, FEMALE);
DataHashMap.put(OCCUPATION, BANKER);

List<String> EligibilityList = new ArrayList<>();

if (HUMAN.equals(DataHashMap.get(SPECIES))) {
EligibilityList.add("H");
if (AMERICAN.equals(DataHashMap.get(NATIONALITY))) {
EligibilityList.add("A");
if (WASHINGTON.equals(DataHashMap.get(STATE))) {
EligibilityList.add("W");
if (FEMALE.equals(DataHashMap.get(GENDER))) {
EligibilityList.add("F");
if (BANKER.equals(DataHashMap.get(OCCUPATION))) {
EligibilityList.add("B");
} else {
EligibilityList.add("NB");
}
} else {
EligibilityList.add("NF");
}
} else {
EligibilityList.add("NW");
}
} else {
EligibilityList.add("NA");
}
} else {
EligibilityList.add("NH");
}
System.out.println(EligibilityList);
我需要使用最合适和最有效的数据结构来修改嵌套的 if-else 结构。任何人都可以建议一种可以有效完成上述工作的数据结构吗?常量、映射和列表需要保持原样(映射是输入,列出输出)。 if-else 逻辑块可以修改

最佳答案

我会将每个条件放在一个列表中进行处理。

        String SPECIES = "SPECIES";
String NATIONALITY = "NATIONALITY";
String STATE = "STATE";
String GENDER = "GENDER";
String OCCUPATION = "OCCUPATION";
String HUMAN = "HUMAN";
String AMERICAN = "AMERICAN";
String WASHINGTON = "WASHINGTON";
String FEMALE = "FEMALE";
String BANKER = "BANKER";

Map<String, String> DataHashMap = new HashMap<>();
DataHashMap.put(SPECIES, HUMAN);
DataHashMap.put(NATIONALITY, AMERICAN);
DataHashMap.put(STATE, WASHINGTON);
DataHashMap.put(GENDER, FEMALE);
DataHashMap.put(OCCUPATION, BANKER);

List<List<String>> lookup = new ArrayList<>();
lookup.add(Arrays.asList(SPECIES, HUMAN, "H", "NH"));
lookup.add(Arrays.asList(NATIONALITY, AMERICAN, "A", "NA"));
lookup.add(Arrays.asList(STATE, WASHINGTON, "W", "NW"));
lookup.add(Arrays.asList(GENDER, FEMALE, "F", "NF"));
lookup.add(Arrays.asList(OCCUPATION, BANKER, "B", "NB"));



List<String> EligibilityList = new ArrayList<>();

for(List<String> item : lookup){
if (item.get(1).equals(DataHashMap.get(item.get(0)))) {
EligibilityList.add(item.get(2));
} else {
EligibilityList.add(item.get(3));
break;
}
}

System.out.println(EligibilityList);

关于java - 使用最合适的数据结构简化嵌套的 if-else 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68104769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com