Reputation: 531
I have a nested if-else block, where a series of conditions are present which need to be executed in a particular order. Below is a sample of the code.
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);
I need to modify the nested if-else structure using the most suitable and efficient data structure. Can anyone suggest a data structure that would do the above job efficiently? The constants, map, and list need to remain as it is (map is the input, and list the output).The if-else logic block can be modified
Upvotes: 2
Views: 230
Reputation: 483
I would hold every condition in a list to process.
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);
Upvotes: 2