Map implementation with duplicate keys

后端 未结 18 1925
暗喜
暗喜 2020-11-22 15:23

I want to have a map with duplicate keys.

I know there are many map implementations (Eclipse shows me about 50), so I bet there must be one that allows this. I know

18条回答
  •  一向
    一向 (楼主)
    2020-11-22 15:57

    We don't need to depend on the Google Collections external library. You can simply implement the following Map:

    Map> hashMap = new HashMap();
    
    public static void main(String... arg) {
       // Add data with duplicate keys
       addValues("A", "a1");
       addValues("A", "a2");
       addValues("B", "b");
       // View data.
       Iterator it = hashMap.keySet().iterator();
       ArrayList tempList = null;
    
       while (it.hasNext()) {
          String key = it.next().toString();             
          tempList = hashMap.get(key);
          if (tempList != null) {
             for (String value: tempList) {
                System.out.println("Key : "+key+ " , Value : "+value);
             }
          }
       }
    }
    
    private void addValues(String key, String value) {
       ArrayList tempList = null;
       if (hashMap.containsKey(key)) {
          tempList = hashMap.get(key);
          if(tempList == null)
             tempList = new ArrayList();
          tempList.add(value);  
       } else {
          tempList = new ArrayList();
          tempList.add(value);               
       }
       hashMap.put(key,tempList);
    }
    

    Please make sure to fine tune the code.

提交回复
热议问题