在工作中有時會看見同事這麼用:

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

  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
  4.   
  5.     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
  6.   
  7. }  

    可以簡潔用for-each中所多使用的程式碼,但map是空時會拋出 nullpoint Excetion

 

以下這範例使用for-each

  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. for (Integer key : map.keySet()) {  
  4.   
  5.     System.out.println("Key = " + key);  
  6.   
  7. }  
  8.   
  9. for (Integer value : map.values()) {  
  10.   
  11.     System.out.println("Value = " + value);  
  12.   
  13. }  

 

此方法雖比較臭長,但卻可省下10%的執行力

 

 

 

    

 

 

  1.  
arrow
arrow
    文章標籤
    Map.Entry<> 使用
    全站熱搜
    創作者介紹
    創作者 JoshS 的頭像
    JoshS

    JoshS的部落格

    JoshS 發表在 痞客邦 留言(0) 人氣()