如何在哈希映射中的哈希映射中允许重复键

时间:2016-04-02 17:31:53

标签: java hash

我的代码是我阅读文档,然后我从每个文档获得术语频率,例如:

术语D1:D1中的术语频率,D2:D2中的术语频率。

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

           String Docs [] = {"word1.txt","word2.txt"};

    for(int i1=0 ; i1<words.length;i1++)

  { String x=words[i1];

    if(!Index.containsKey(x) || Index.isEmpty())
    {
      HashMap<Integer, Integer> inner = new HashMap<Integer, Integer>();

      inner.put(i, 1);

      Index.put(x,inner);

    }

  else if(Index.containsKey(x))
    {
        if(Index.get(x).containsKey(i))

        { 
                 HashMap<Integer, Integer> inner = new HashMap<Integer, Integer>();
                    Collection<Integer> value= Index.get(x).values() ;

                   int count=(int) value.toArray()[0];

                   count=count+1;

                   inner.put(i, count);

                   Index.put(x,inner);

        }

        else if(!Index.get(x).containsKey(i))

        {
        HashMap<Integer, Integer> inner = new HashMap<Integer, Integer>();

          inner.put(i, 1);

            Index.put(x,inner);

            }


    }

Word1包含:欢迎欢迎构建故事欢迎

word2包含:build

我的输出:

  

build:{1 = 1} welcome:{0 = 3} story:{0 = 1}

我希望我的输出是这个

  

构建:{0 = 1,1 = 1}欢迎:{0 = 3}故事:{0 = 1}

所以为什么不允许这种情况发生

1 个答案:

答案 0 :(得分:3)

一般来说,HashMapMap只能包含唯一键,不能重复。允许重复键的地图类型称为 multimap 。 Java标准库中没有实现,但优秀的Guava具有a Multimap interface各种实现。