This is an extension of my previous question How to add values in a multi map
I was able to add the values in a multi map but the problem is when it finds duplicate keys it should add the values corresponding to its keys. Then once the current key changes to another number it should make the sum =0.00 and then start over again with a different duplicate key number. In the following code I don't know where to make the sum=0.00 and where to print the value so it only prints out key with the summed up value.
Here is the code (UPDATED CODE):
// create a Map()
Map<String, String> readValuemap = new LinkedHashMap<String,String>();
String val = null;
for(int i =0; i< 256;i++){
for(int y=0; y< 256; y++){
//reading in the values.
String x = image.getLocationAsString(i, y);
String n = image.getValueAsString(i, y);
//Parsing them into "key" and "value".
String delim = ", value=";
String [] tokens = n.split(delim);
double num = Double.parseDouble(tokens[1]);
String stringNum = String.valueOf(num);
String [] t = x.split("r=");
String[] b = t[1].split(" mm/c");
//System.out.print("Meet b: "+b[0]);
double radius = Double.parseDouble(b[0]);
String stringRad = String.valueOf(radius);
//System.out.println("The radius: "+radius);
//retrieve the current value for the key from the map.
val = readValuemap.get(radius);
System.out.println(val);
//if null, just put the value into the map.
if(val == null){
readValuemap.put(stringRad, stringNum);
System.out.println("new if; "+val);
}
else{
//if not null, add the current value to the new value (the one that you just read in)
//and store the sum in the map.
double v = Double.parseDouble(val);
v += num;
String newValue = String.valueOf(v);
System.out.println("new value; "+newValue);
readValuemap.put(stringRad, newValue);
}
}
}
System.out.println("-------------Printing out the values----------------");
Iterator iter = readValuemap.entrySet().iterator();
while(iter.hasNext()){
Map.Entry pairs = (Map.Entry)iter.next();
System.out.println(pairs.getKey() + " = "+ pairs.getValue());
}
So basically it should be like this: the multimap contains:
1.36 = 59.0
1.36 = 65.0
1.35 = 56.0
1.35 = 71.0
1.34 = 64.0
1.34 = 75.0
1.33 = 59.0
Afterwards it should be like this (it should find any duplicate keys in the multimap and add the values):
1.36 = 124.0
1.35 = 127.0
1.34 = 139.0
1.33 = 59.0
Write now its just adding all the values regardless if the key is a duplicate or not.