有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

插入Hashmaps的Hashmap,Java

我有这个功能:

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

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

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

也就是说,如果我们在文档(docID)中找到单词(token)'the'10 times'5',我想要一个包含这些信息的结构,比如: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);
                }

            } 
   }

共 (3) 个答案

  1. # 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

  2. # 2 楼答案

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

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

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

    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);
    }