2012-06-26 50 views
0
Map<String, List<String>> words = new HashMap<String, List<String>>(); 
      List<Map> listOfHash = new ArrayList<Map>(); 

      for (int temp = 0; temp < nList.getLength(); temp++) { 
       Node nNode = nList.item(temp); 
       if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
        Element eElement = (Element) nNode; 
        String word = getTagValue("word", eElement); 
        List<String> add_word = new ArrayList<String>(); 
        String pos = getTagValue("POS", eElement); 
        if(words.get(pos)!=null){ 
         add_word.addAll(words.get(pos)); 
         add_word.add(word); 
        } 
        else{ 
         add_word.add(word); 
        } 
        words.put(pos, add_word); 
       } 
      } 

這是我寫的一段代碼(它使用Stanford CoreNLP)。我面臨的問題是,目前這個代碼只與一個地圖即「單詞」一起工作。現在,我希望只要解析器看到「000000000」是我的分隔符,就應該將新的Map添加到List中,然後將鍵和值插入到它中。如果沒有看到「000000000」,則鍵和值將被添加到相同的地圖中。 請幫助我,因爲即使經過很多努力,我也無法做到這一點。HashMap的列表Java

+0

您能否舉個例子? –

回答

2

我猜listOfHash是包含所有地圖...

所以改名wordscurrentMap例如,添加到它。當你看到「000000000」實例化一個新的地圖,將其分配給currentMap,將它添加到列表中,並繼續...

類似:

if ("000000000".equals(word)){ 
    currentMap = new HashMap<String, List<String>>(); 
    listOfHash.add(currentMap); 
    continue; // if we wan't to skip the insertion of "000000000" 
} 

而且不要忘記添加初始映射到listOfHash。

我也看到您還有其他問題,您的代碼,這裏是修改後的版本(我沒試過編譯):

Map<String, List<String>> currentMap = new HashMap<String, List<String>>(); 
List<Map> listOfHash = new ArrayList<Map>(); 
listOfHash.add(currentMap); 


for (int temp = 0; temp < nList.getLength(); temp++) { 
    Node nNode = nList.item(temp); 
    if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
     Element eElement = (Element) nNode; 
     String word = getTagValue("word", eElement);  

     if ("000000000".equals(word)){ 
      currentMap = new HashMap<String, List<String>>(); 
      listOfHash.add(currentMap); 
      continue; // if we wan't to skip the insertion of "000000000" 
     } 

     String pos = getTagValue("POS", eElement); 

     List<String> add_word = currentMap.get(pos); 
     if(add_word==null){ 
      add_word = new ArrayList<String>(); 
      currentMap.put(pos, add_word); 
     } 
     add_word.add(word); 
    } 

} 
+0

thanx很多pgras ..但你實際上是什麼意思是「不要忘記將你的初始地圖添加到listOfHash」。你能解釋一下嗎? – agarwav

+0

我已經給出了更完整的回覆... – pgras

+0

我需要用「currentMap」替換「words」,因爲你沒有在這裏做過。和thanx很多 – agarwav