1

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;    
        ...
    }
}
Naman
  • 27,789
  • 26
  • 218
  • 353
Jane
  • 9
  • 5
  • Why do you want to shorten it? It seems to meet the requirements. – Joshua Drake Sep 26 '17 at 02:37
  • @JoshuaDrake - under the switch model, the number of string comparisons increases linearly with the number of mappings - O(n) - which could get quite taxing if the logic is executed multiple times (e.g. in a loop). Fetching from a HashMap should be a lot better than O(n) - https://stackoverflow.com/a/4553642/79450 – Catchwa Sep 26 '17 at 02:55
  • @Catchwa HashMap is a fine recommendation, I've upvoted your answer. I've found that questions like this one often obscure underlying assumptions or misunderstandings, and further clarifications can lead to more complete responses, especially when navigating them from a review queue. I even think your answer could be improved by inclusion of the context provided in your comment. – Joshua Drake Sep 26 '17 at 07:56

2 Answers2

2

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());
Catchwa
  • 5,845
  • 4
  • 31
  • 57
0

One way to shorten it is by moving the switch to its own method:

private String getDepartmentAbbreviation(String departmentName) {
    switch(departmentName.toLowerCase()) {
        case "business management":
            return "SBM";
        case "chemical & life sciences":
            return "SCL";
        case "design":
            return "SDN";
        case "engineering":
            return "SEG";
        case "oral health therapy":
            return "SHS(AH)";
    }
    return null;
}

//...
departmentName = getDepartmentAbbreviation(departmentName);
//...
shmosel
  • 49,289
  • 6
  • 73
  • 138