java- hashmap一个键和多个值替代将值部分存储在List中

时间:2017-12-12 07:46:26

标签: java hashmap

通常,当您在哈希映射中为同一个键设置多个值时,我找到的答案将使用ListArrayList来存储值部分。例如:

Map<Object,ArrayList<Object>> multiMap = new HashMap<Object,ArrayList<Object>>();

我想知道可以保留hashmap的正常定义并将任何新值附加到旧值(以逗号分隔)。像这样:

Map<String, String> memOf = new HashMap<String, String>();
    Map<String, String> subOrg = new HashMap<String, String>();
    Map<String, String> email = new HashMap<String, String>();

 String line="";
    String source="";
    String sub="";
    String obj="";
    String hashKey="";
    String hashVal="";


    for (Text value : values){ //start iterate over values 
        line=value.toString();
        String[] parts=line.trim().split(",");



    source=parts[0].trim();
    sub=parts[1].trim();
    obj=parts[2].trim();
    hashKey=sub;



    if (source.equals("memberOf")){
        hashVal=memOf.get(hashKey);
        if (hashVal!=null){
        hashVal=hashVal+","+obj;
        memOf.put(hashKey, hashVal);
        } 
    }

}

前面的代码是填充哈希映射,旁边读取单个值使用split(",")并将它们存储在String数组中。类似的东西:

for (String key1 : memOf.keySet()) {             
    x=key1;
    String[] y=memOf.get(x).toString().split(",");

    int numberOfItems = y.length;
        for (int i=0; i<numberOfItems; i++){  
    System.out.println(y[i]); 
    }
}

1 个答案:

答案 0 :(得分:0)

  

我想知道可以保留hashmap的正常定义并将任何新值附加到旧值(以逗号分隔)。

你已经做到了。以低效的方式,但你做到了。

正如Andy Turner在评论中所指出的那样,您可能会寻找像Guava MultiMap这样的实现,它允许将单个键映射到多个值。

除此之外,official Map documentation 不会报告将一个值添加到另一个值的功能,只会替换它。对于整数,您可以increment them pretty easily,但是对于其他人,您必须自己做或者找到更有效的方法(例如ArrayList)。

相关问题