2017-03-09 66 views
2

我有这样的功能:插入到包含HashMap的是HashMap,Java的

public void insert(String token, int docID) 
    { 
     insertNormIdx(token, docID); 
    } 

正在由主程序不断调用。 docID是一个文档的ID,token是我们在文档中找到的一个词。

所以这个函数被调用很多次,直到所有的文档都被解析。我想要做的是创建一个包含一个条目docID的hashmap,这应该指向另一个包含我们在文档中找到的单词(令牌)的hashmap。

也就是说,如果我们在文档(docID)'5'中找到10次单词(标记)'the',我想要一个保存这些信息的结构,如:5,the,10。

这是我做了什么,但它并没有真正的工作,只保留第一个字从文件:

HashMap<Integer, HashMap<String, Integer>> normal_idx = new HashMap<Integer, HashMap<String, Integer>>(); 

    public void insertNormIdx(String token, int docID) 

    { 
     HashMap<String, Integer> val = new HashMap<String, Integer>(); 

     if(!normal_idx.containsKey(docID)) 
     { 

      val.put(token, 1); 
      normal_idx.put(docID, val); 
     } 

     if (normal_idx.containsKey(docID)) 
      { 

       if (normal_idx.get(docID).get(token)!=null) 
       { 
        val.put(token, normal_idx.get(docID).get(token)+1); 

        normal_idx.put(docID, val); 
       } 

      } 
    } 

回答

2

有一个在你的代码有很多冗余和错误的。在你的问题的具体问题是因为没有else这个if

if (normal_idx.get(docID).get(token)!=null) 

因此新的令牌从来没有插入。

但整个代码可以显着提高。在Java 8中,您可以替换整个方法:

normal_idx.computeIfAbsent(docID, k -> new HashMap<>()) 
     .merge(token, 1, Integer::sum); 

如果你在较早的Java版本,你可以试试这个:

HashMap<String, Integer> val = normal_idx.get(docID); 
if (val == null) { 
    val = new HashMap<String, Integer>(); 
    normal_idx.put(docID, val); 
} 

Integer count = val.get(token); 
if (count == null) { 
    val.put(token, 1); 
} else { 
    val.put(token, count + 1); 
} 
+0

这个衬垫......脑海=吹,谢谢 –

1

更好的方式来做到这一点:

public void insertNormIdx(String token, int docID) { 
    Map<String, Integer> doc = normal_idx.get(docId); 
    if (doc == null) { 
     normal_idx.put(docId, doc = new HashMap<String, Integer>()); 
    } 
    Integer counter = doc.get(token); 
    if (counter == null) 
     doc.put(token, 1); 
    else 
     doc.put(token, ++counter); 
} 

顺便说一下,不要只使用裸HashMap,创建类Document

1

您可以使用Java 8的computeIfAbsent方法把/合并值映射,例如:

public void insertNormIdx(String token, int docID) { 
    normal_idx.computeIfAbsent(docID, k -> new HashMap<>()).merge(token, 1, (old, one) -> old + one); 
}