Search code examples
javamultimap

How to add values in a multi map


I can't seem to figure this out even after look at this: Adding values of two maps whenever there is a key match. I made a multi map that contains radius as keys and the amplitude as values. But there are duplicates of keys. So I want to traverse the whole map and if there are duplicate keys I want to add the values of those keys. I have tried adding it to a new map or a double sum but I can't seem to get it to work. What am I missing.

      Multimap<String, String> multimap = LinkedListMultimap.create();
      for(......){
            String newRad = String.valueOf(radius);
            String val = String.valueOf(num);
            multimap.put(newRad, val);
      }
       ........
          double s=0.00;
         //java.util.Map multimap2;
         Multimap<Double, Double> multimap2 = LinkedListMultimap.create();
         Iterator it = multimap.entries().iterator();

            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry)it.next();
                double currentKey = Double.parseDouble((String) pairs.getKey());
                String newRad = String.valueOf(1.83);
                if(multimap.containsKey(newRad)){
                    double values = Double.parseDouble((String) pairs.getValue());
                    s += values;
                    System.out.println(s);
                }
                else{
                    s = 0.00;
                }

                System.out.println(pairs.getKey() + " = " + pairs.getValue());
                //it.remove(); // avoids a ConcurrentModificationException
            }

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

UPDATE: So I am being able to add the values but I thinks its adding all the value in the map not just the ones with the duplicate. I tried it on 1.83 and it gives me values like 7337061.0 and it keeps increasing. What is wrong with my if statement?


Solution

  • Never ever use Doubles as a key to a map, for the same reason that you should never ever compare floating point values (float and double) using == - different binary values may be very close to each other and have the same representation when printed or converted to String, but they will have a different hashCode() and will not match using equals().

    I would suggest converting to an integer or to string forms - f.e. if you need 2 decimal digit accuracy, use (int)(value*100) as the key, or use a specific NumberFormat to convert them to Strings.