如何优化以下代码段?

时间:2017-01-03 04:47:30

标签: java if-statement

以下代码段显示了基于名称的类型

public static List<String> LANGUAGES = Arrays.asList("js", "java", "html");
public static List<String> LIBRARIES = Arrays.asList("jquery", "ember");
public static List<String> BROWSERS = Arrays.asList("chrome", "safari", "mozilla");
public static List<String> MAIL = Arrays.asList("gmail", "yahoo");
public static List<String> EDITORS = Arrays.asList("vim", "vi", "notepad");

public static getType(String name) {

String type = null;
if(LANGUAGES.contains(name)) {
  type = "languages";
} else if(LIBRARIES.contains(name)) {
  type = "libraries";
} else if(BROWSERS.contains(name)) {
  type = "browsers";
} Else if (MAIL. contains (name)) {
  type = "mail";
}else if(EDITORS.contains(name)) {
  type = "editors";
}
return type
}

想用switch语句尝试相同的想法。但是,switch并没有提供用Java检查list.contains的选项。

有没有办法以更好的方式编写上述代码段?因为getType方法在添加新类型的情况下不断增长。

1 个答案:

答案 0 :(得分:2)

最好使用地图:

public static List<String> LANGUAGES = {"js", "java", "html"};
public static List<String> LIBRARIES = {"jquery", "ember"};
public static List<String> BROWSERS = {"chrome", "safari", "mozilla"};
public static List<String> MAIL = {"gmail", "yahoo"};
public static List<String> EDITORS = {"vim", "vi", "notepad"};

private static Map<String, String> categories= new HashMap<>;
static {
      // build the above map:
      LANGUAGES.forEach(e -> categories.put(e, "languages"));
      LIBRARIES.forEach(e -> categories.put(e, "libraries"));
      ...
}

public static getType(String name) {
      return categories.get(name);
}