Usually when you have multiple values for the same key in hash map the answers I have found would use a List
or ArrayList
to store the value part. For example:
Map<Object,ArrayList<Object>> multiMap = new HashMap<Object,ArrayList<Object>>();
I was wondering it was possible to keep the normal definition of hashmap and append any new values to the old value (comma separated). Something like this:
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);
}
}
}
The previous code is to populate the hashmaps and next to read individual values use split(",")
and store them in a String array. something like:
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]);
}
}