缩短开关盒方法

时间:2017-09-26 01:56:43

标签: java switch-statement

我想说我是Java新手。所以我有一个很长的switch-case语句代码,可以缩短它吗?

以下是代码:

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;    
        ...
    }
}

2 个答案:

答案 0 :(得分:2)

创建一个如此填充的HashMap<String,String>

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

然后,只需从地图中进行查找,而不是进行切换。

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

答案 1 :(得分:0)

缩短它的一种方法是将switch移动到自己的方法:

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);
//...