[英]Find a string in list of lists
我有超過15個字符串列表,每個列表包含幾個不同的代碼。 每個列表包含一種特定類型的代碼。 我有一個輸入代碼,必須找出該輸入代碼屬於哪個列表,並根據結果返回一個特定的String。 我已經使用過,如果要這樣做。 下面是示例代碼
private static String getCodeType(String inputCode) {
if (MyClass.getCodeTypeOneList().contains(inputCode)) {
return "CodeType_A";
} else if (MyClass.getCodeTypeTwoList().contains(inputCode)) {
return "CodeType_B";
} else if (MyClass.getCodeTypeThreeList().contains(inputCode)) {
return "CodeType_C";
} else if (MyClass.getCodeTypeFourList().contains(inputCode)) {
return "CodeType_D";
} else if (MyClass.getCodeTypeFiveList().contains(inputCode)) {
"CodeType_E;
} else if (MyClass.getCodeTypeixList().contains(inputCode)) {
return "CodeType_F";
} else if (MyClass.getWithDrawalCodeTypeList().contains(inputCode)) {
return "CodeType_G";
}
// similar 10 more if conditions
else {
return null;
}
}
每個列表如下:public static List codeTypeOneList = new ArrayList();
public static final List<String> getCodeTypeOneList() {
codeTypeOneList.add("AFLS");
codeTypeOneList.add("EAFP");
codeTypeOneList.add("ZDTC");
codeTypeOneList.add("ZFTC");
codeTypeOneList.add("ATCO");
return codeTypeOneList;
}
(其他代碼類型的類似列表)
有沒有更好的方法來實現這一目標? 謝謝
作為一次性步驟,構建地圖:
Map<String, String> codeTypeMap = new HashMap<>();
for (String key : getCodeTypeOneList()) {
codeTypeMap.put(key, "CodeType_A");
}
for (String key : getCodeTypeTwoList()) {
codeTypeMap.put(key, "CodeType_B");
}
// ...
(您需要確保多個列表中都沒有list元素;或者以相反的優先順序添加它們,以便以后的代碼類型覆蓋以前的代碼類型)。
然后,只需使用codeTypeMap.get
查找給定代碼的類型。
private static String getCodeType(String inputCode) {
return codeTypeMap.get(inputCode);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.