在工作中有時會看見同事這麼用:
public static Map<String,List<String>> gatherCode ;
static{
gatherCode = new HashMap<String,List<String>>();
List<String> A1E = new ArrayList<String>(){
{
add("A11");
add("A12");
}
};
List<String> B1E = new ArrayList<String>(){
{
add("B11");
add("B12");
}
};
gatherCode.put("A1E", A1E );
gatherCode.put("B1E", B1E );
}
public String getCode(String requestCode){
String Code = null;
// 目前式 Map.Entry<> <>內只能塞能容納null的屬性 如Integer , String 而不可塞 int等
for (Map.Entry<String, List<String>> entry : gatherCode.entrySet()) {
List<String> codeList = entry.getValue();
for(String codeString:codeList){
if(codeString.equals(requestCode)){
return entry.getKey();
}
}
}
return Code ;
}
上方code看似簡便但下面要說的是使用Map.Entry的壞處
下面範例參考至:http://blog.csdn.net/tjcyjd/article/details/11111401
以下這例子中 使用entrySet
- Map<Integer, Integer> map = new HashMap<Integer, Integer>();
- for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
- System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
- }
可以簡潔用for-each中所多使用的程式碼,但map是空時會拋出 nullpoint Excetion
以下這範例使用for-each
- Map<Integer, Integer> map = new HashMap<Integer, Integer>();
- for (Integer key : map.keySet()) {
- System.out.println("Key = " + key);
- }
- for (Integer value : map.values()) {
- System.out.println("Value = " + value);
- }
此方法雖比較臭長,但卻可省下10%的執行力