Jane Jane - 23 days ago 9
Java Question

Shorten switch case method

I would like to say that I am new to Java. So I have a long code of a switch-case statement, it is possible to shorten it?

Here is the code:

String[] department = line.split(cvsSplitBy);
String departmentName = department[0];
String email = department[3];

if (departmentName == null) return;
switch(departmentName.toLowerCase()) {
case "business management":
departmentName = "SBM";
break;

case "chemical & life sciences":
departmentName = "SCL";
break;

case "design":
departmentName = "SDN";
break;

case "engineering":
departmentName = "SEG";
break;

case "oral health therapy":
departmentName = "SHS(AH)";
break;
...
}
}

Answer Source

Create a HashMap<String,String> that you populate like so:

HashMap<String, String> map = new HashMap<String, String>();
map.put("business management", "SBM");
//etc, etc.

Then, just do a lookup from your map instead of doing a switch.

departmentName = map.get(departmentName.toLowerCase());