对 TreeMap 中的数组求和

Sum arrays from TreeMap

我有多个数组存储在一个 TreeMap 中,然后我想检索这些数组并将它们乘以一个数字。之后我想将每个列值加到一个新数组中。

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class readingLargeFile {
    static String[] words;
    static  Map<String, double[]> m1 = new TreeMap();
    static Map<String,Double> m2 = new TreeMap();
    public static void main(String args[]){
        //First TreeMap
         double count[]={3.9, 1.2, 6.2, 1.8, 7.6, 3.8};
         double count1[]={1.6, 7.2, 6.2, 2.3, 1.8, 0.0};
         double count2[]={1.6, 5.5, 1.8, 8.8, 0.0, 0.0};
         double count3[]={0.0, 0.0, 0.0, 2.3, 0.0, 0.0};
         double count4[]={2.0, 2.2, 1.2, 3.9, 2.3, 4.4};
         double count5[]={3.4, 0.0, 1.9, 2.4, 0.5, 2.0};
            m1.put("apple",count);
            m1.put("orange",count1);
            m1.put("banana",count2);
            m1.put("cherry",count3);
            m1.put("lemon",count4);
            m1.put("strawbarry",count5);

        //for(Map.Entry<String, double []> e : m1.entrySet()) {//print First TreeMap content

        //System.out.println(e.getKey()+":"+Arrays.toString(e.getValue()));
            //}

               //second TreeMap
        m2.put("apple", 2.1);
        m2.put("cherry", 1.9);
        m2.put("grasb", 3.0);
        m2.put("strawbarry", 4.1);

        double[] finalSum = new double[6];
        double first=0;
        double second=0;
        double third=0;
        double fourth=0;
        double fifth=0;
        double sixth=0;

        String key="";
                 for ( Map.Entry<String,Double> entry : m2.entrySet() ) {//for loop through the second TreeMap
                      if ( m1.containsKey(entry.getKey()) ) {//check if the first TreeMapp contain same key from second TreeMap
                          //if the key is common in m1 and m2, multiply the values

                          key=entry.getKey();
                       double y=entry.getValue();//the number from second TreeMap 
                       double w[]=m1.get(entry.getKey());//the array from first TreeMap
                       //for loop to multiple the array from first TreeMap by the number in second TreeMap for same key
                       /*for example if the key=apple
                         then
                         {3.9*2.1, 1.2*2.1, 6.2*2.1, 1.8*2.1, 7.6*2.1, 3.8*2.1}
                         */ 
                       for (int u=0;u<w.length;u++){
                           finalSum[u]=  w[u]*y;}
                       System.out.println(key+"     "+Arrays.toString(finalSum));
                       }}


                 for (int u=0,t=0;u<finalSum.length;u++,t++){
                   first+=finalSum[t];
                   second+=finalSum[t];
                   third+=finalSum[t];
                   fourth+=finalSum[t];
                   fifth+=finalSum[t];
                   sixth+=finalSum[t];
                 }
                   System.out.println(first+"\n"+second+"\n"+third+"\n"+fourth+"\n"+fifth+"\n"+sixth);}}

然后这是我的输出:

apple     [8.19, 2.52, 13.020000000000001, 3.7800000000000002, 15.959999999999999, 7.9799999999999995]
cherry     [0.0, 0.0, 0.0, 4.369999999999999, 0.0, 0.0]
strawbarry     [13.939999999999998, 0.0, 7.789999999999999, 9.839999999999998, 2.05, 8.2]
41.81999999999999
41.81999999999999
41.81999999999999
41.81999999999999
41.81999999999999
41.81999999999999

谁知道问题出在哪里。:(

我猜你应该定义 int t=0;在 for 循环之前。虽然不确定

最终编辑 在重构问题之后,我对之前提出的解决方案进行了更改,但仍然使用相同的方法,详情请参见下面的"original answer"

这是问题的最终修复代码,解决了之前所述的问题。

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class ReadingLargeFile {
    static String[] words;
    static Map<String, double[]> m1 = new TreeMap();
    static Map<String, Double> m2 = new TreeMap();

    public static void main(String args[]) {
        //First TreeMap
        double count[] = {3.9, 1.2, 6.2, 1.8, 7.6, 3.8};
        double count1[] = {1.6, 7.2, 6.2, 2.3, 1.8, 0.0};
        double count2[] = {1.6, 5.5, 1.8, 8.8, 0.0, 0.0};
        double count3[] = {0.0, 0.0, 0.0, 2.3, 0.0, 0.0};
        double count4[] = {2.0, 2.2, 1.2, 3.9, 2.3, 4.4};
        double count5[] = {3.4, 0.0, 1.9, 2.4, 0.5, 2.0};
        m1.put("apple", count);
        m1.put("orange", count1);
        m1.put("banana", count2);
        m1.put("cherry", count3);
        m1.put("lemon", count4);
        m1.put("strawbarry", count5);

        //second TreeMap
        m2.put("apple", 2.1);
        m2.put("cherry", 1.9);
        m2.put("grasb", 3.0);
        m2.put("strawbarry", 4.1);

        double[][] addedresults = getFinalSums(m1, m2);
        double[] finalResults = getSummedColumns(addedresults);

        System.out.println("added value arrays: " + Arrays.deepToString(addedresults));
        System.out.print("final summed array: " + Arrays.toString(finalResults));

    }

    public static double[] getSummedColumns(double[][] array) {
        double[] results = new double[array.length];
        for (int i = 0; i < results.length; i++) {
            for (int j = 0; j < array.length; j++) {
                results[i] += array[j][i];
            }
        }
        return results;
    }

    public static double[][] getFinalSums(Map<String, double[]> m1, Map<String, Double> m2) {

        int sharedSums = 0;
        for (Map.Entry<String, Double> entry : m2.entrySet())
            if (m1.containsKey(entry.getKey()))
                sharedSums++;

        double[][] finalSum = new double[sharedSums][];

        int i = 0;
        for (Map.Entry<String, Double> entry : m2.entrySet()) {//for loop through the second TreeMap
            if (m1.containsKey(entry.getKey())) {//check if the first TreeMapp contain same key from second TreeMap
                //if the key is common in m1 and m2, multiply the values

                double y = entry.getValue();//the number from second TreeMap
                double w[] = m1.get(entry.getKey());//the array from first TreeMap

                finalSum[i] = new double[w.length]; // instantiate the new array in the 2d array

                for (int j = 0; j < w.length; j++) {
                    finalSum[i][j] = w[j] * y; // add in the values in the correct spot in the 2d array
                }
                i++; // increase the current spot in the 2d array
            }
        }
        return finalSum;
    }
}

这是 class

产生的输出

added value arrays: [[8.19, 2.52, 13.020000000000001, 3.7800000000000002, 15.959999999999999, 7.9799999999999995], [0.0, 0.0, 0.0, 4.369999999999999, 0.0, 0.0], [13.939999999999998, 0.0, 7.789999999999999, 9.839999999999998, 2.05, 8.2]]

final summed array: [22.129999999999995, 2.52, 20.810000000000002]

编辑原始答案

for (int u=0;u<w.length;u++){
    finalSum[u]=  w[u]*number;//multibly the array with the number                              
    System.out.println(Arrays.toString(finalSum));}//print the array
}

注意你是如何每次都写出结果的,但是在循环的下一个 运行 中,你正在覆盖结果,这是你需要二维数组的地方,如 [=16] =]

double[][] finalSum = new int[w.length][];

for(int i = 0; i < w.length; i++){
    for (int u=0;u<w.length;u++){
            finalSum[i][u]=  w[u]*number;//multibly the array with the number                              
            System.out.println(Arrays.toString(finalSum));}//print the array
    }
}

现在数组的每一行都应该保存在二维数组中,然后可以如下所述访问和求和

已编辑 现在按要求添加列,仍然假设它是一个二维数组结构

我认为您面临的问题是您总结数据的方式。

做了一个小例子来展示如何对二维数组中的列值求和

public class NewClass {
    public static void main(String[] args){
        NewClass newClass = new NewClass();
        newClass.method();
    }

    public void method(){
        int[][] array = new int[6][6];
        int[] results = new int[6];
        for(int i = 0; i < array.length; i++)
            for(int j = 0; j < array.length; j++) {
            if(i <= array.length/2)
                array[i][j] = j * i;
            else
                array[i][j] = j+i;
            }
        for(int i =0; i < results.length; i++)
        {
            for(int j = 0; j < array.length; j++)
            {
                results[i] += array[j][i];
            }
        }
        System.out.println("Array" + Arrays.deepToString(array));
        System.out.println("results: " + Arrays.toString(results));
    }
}

这会产生这样的输出

Array[[0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10], [0, 3, 6, 9, 12, 15], [4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9, 10]]

results: [9, 17, 25, 33, 41, 49]

请注意,当值包含 list/array 时,TreeMap 也是一组 2 列表,因此基于其余代码的类似方法是适用的

您可以iterate通过Map并使用Java 8的stream计算总和,例如:

Map<String, double[]> data = new TreeMap<>(); // Map of double arrays
for(Map.Entry<String, double[]> entry : data.entrySet()){
    System.out.println(Arrays.stream(entry.getValue()).sum());

}

更新

如果你想要sum的列相乘后,你可以使用如下:

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

double count[] = { 3.9, 1.2, 6.2, 1.8, 7.6, 3.8 };
double count1[] = { 1.6, 7.2, 6.2, 2.3, 1.8, 0.0 };
double count2[] = { 1.6, 5.5, 1.8, 8.8, 0.0, 0.0 };
double count3[] = { 0.0, 0.0, 0.0, 2.3, 0.0, 0.0 };
double count4[] = { 2.0, 2.2, 1.2, 3.9, 2.3, 4.4 };
double count5[] = { 3.4, 0.0, 1.9, 2.4, 0.5, 2.0 };
m1.put("apple", count);
m1.put("orange", count1);
m1.put("banana", count2);
m1.put("cherry", count3);
m1.put("lemon", count4);
m1.put("strawbarry", count5);

m2.put("apple", 2.1);
m2.put("cherry", 1.9);
m2.put("grasb", 3.0);
m2.put("strawbarry", 4.1);

for(Map.Entry<String, double[]> entry : m1.entrySet()){
    if(m2.containsKey(entry.getKey())){
        double multiplier = m2.get(entry.getKey());
        double[] values = entry.getValue();
        for(int i=0 ; i<values.length ; i++){
            values[i] = values[i] * multiplier;
        }
    }
}

//Multiplication done, now sum the columns
double sum = 0;
for(int i = 0; i<6 ; i++){
    for(Map.Entry<String, double[]> entry : m1.entrySet()){
        sum += entry.getValue()[i];
    }
    System.out.println(sum);
    sum = 0;
}