2017-04-16 102 views
3

我有一張地圖,其值是一個整數列表。如果在讀卡器中找到密鑰,我必須向列表中添加一個整數。我有下面的代碼,除了一個以外每次都有效。換句話說,如果密鑰存在5次,列表將會說它只有4次。我錯過了什麼?謝謝!在地圖中正確填充列表

Map<String, List<Integer>> map = new TreeMap<String, List<Integer>>(); 
String key; // the string from my reader 

if (map.containsKey(key)) { 
    map.get(key).add(value); //value being an integer gotten earlier 
} 

我的代碼已經被添加的鑰匙地圖在構造函數中,像這樣:

while (reader.ready()) { 
    key = reader.readLine(); 
    if(!key.isEmpty()) { 
     map.put(key, new ArrayList<Integer>()); 
    } 
}  

我不需要做任何事情,如果關鍵是沒有找到,只需添加值幾時。

回答

0

您發佈的代碼片段並不是您的實際完整代碼,但無論如何,您需要有邏輯來處理第一次看到密鑰。在第一種情況下,您應該初始化要存儲在地圖中的整數列表。類似這樣的:

public static void addValue(String key, Integer value, 
    Map<String, List<Integer>> map) { 
    List<Integer> list = map.get(key); 
    if (list == null) { 
     list = new ArrayList<>(); 
    } 
    list.add(value); 
} 

public static void main(String[] args) { 
    Map<String, List<Integer>> map = new TreeMap<String, List<Integer>>(); 
    String key; // the string from my reader 
    Integer value; 
    addValue(key, value, map); 
} 
0

如果找不到密鑰,該如何處理?我懷疑如果未找到密鑰,則錯過將第一個Integer值添加到列表中。

if (map.containsKey(key)) { 
    map.get(key).add(value); //value being an integer gotten earlier 
} else { 
    List<Integer> list = new ArrayList<>(); 
    list.add(value); //add value to the list 
    map.put(key, list); 
} 
0

希望這可以幫助您解決問題。

//if key not exists insert key  
    if(!map.containsKey(key)){ 
      List<Integer> list = new ArrayList<Integer>(); 
      list.add(value); 
      map.put(key,list); 
     } 
    //if key exists do this... 
    else{ 
      List<Integer> list = new ArrayList<Integer>(); 
      //Getting previous existing elements on map at that index and adding to list back 
      list.addAll(map.get(key)); 
      map.put(list); 
     } 
0

您還沒有提到要這不能不映射值只有當它是同一個列表,你可以使用Java 8

map.entrySet().forEach(entry -> { 
     if ("5" == entry.getKey()) { 
      ((List) entry.getValue()).add(5); 
      System.out.println(entry.getValue()); 
     } 
}); 
修改同一個列表