Search code examples
javamatrixtreemap

Compare two TreeMap


I have two TreeMap

The first map is:

Map<String, Double> m1 = new TreeMap();

and the second is:

Map<String,double []> m2 = new TreeMap();

I want to search the Key in first map to the second one, and then multiply the value of the first map to the list of second map values (for the similar keys). After that I will Have an array of type double from the multiplication, then I want to sum the values for each index independent.

For Example:

Map 1:

Apple : 1.0
Cat:2.1
Dog:1.2

Map2:

Apple:{2.0,0.0,4.0}
Dog {1.1,0.0,0.0}
Moon:{0.0,5.0,2.0}

The Result will Be:

Apple{2.0,0.0,4.0}
Dog{1.32,0.0,0.0}

Then the summation :

{3.32,0.0,4.0}

This is my try, I do the search between the two matrixes, then I do the multiplication .

***My question how can I do the summation for each index and how to retrieve a value for spesfic index.

    for ( Map.Entry<String,Double> entry : m1.entrySet() ) {
 List<Double> myList = new ArrayList<Double>();
     if ( m2.containsKey(entry.getKey()) ) {
         //if the key is common in map1 and map2, compare the values
                    double y=entry.getValue();
                    double j[]=m2.get(entry.getKey());
                   for (int u=0;u<j.length;u++){
                       myList.add(j[u]);
                   }
                   for (int i=0;i<myList.size();i++){

                    System.out.println(entry.getKey()+" "+myList.get(i)*y);
                 }
               }}

Solution

  • Given the commutative property of addition, keep the total sum array outside of the loop and for every matched keys, add the current index i of the total sum array to the product of y and j[i].

    Let's assume a size N for the array. Then:

    double[] finalSum = new double[N];
    
    for ( Map.Entry<String,Double> entry : m1.entrySet() ) {
         if ( m2.containsKey(entry.getKey()) ) {
             //if the key is common in map1 and map2, compare the values
             double y=entry.getValue();
             double j[]=m2.get(entry.getKey());
             for (int u=0;u<j.length;u++){
                 finalSum[u] += y * j[u];
             }
         }
    }