2012-06-26 104 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