Jane Jane - 5 months ago 23
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";

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

case "design":
departmentName = "SDN";

case "engineering":
departmentName = "SEG";

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

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download