Santhucool
Santhucool

Reputation: 1706

Add up the column values in while loop if it comes repetedly

I am creating a table from ajax and the getting of values using a while loop:

while (rstdb.next()) {
        rstdb.getInt(1)+"~"+ rstdb.getInt(2);
}

In my while loop my rstdb.getInt(1) will be 2,2,2,2,2,3,3...... and second values rstdb.getInt(2) are 10,20,30,40,50,10,20,.....

I need to sum up the values specific to 2 and values specific to 3 seperate.

ie,

enter image description here

It means 10+20+30+40+50 =150 for 2 and 10+20 =30 for 3.

It may contain single values also for example it may have 4,5,5,6,7,7....

How can I do that?

I need something like:

while (rstdb.next()) {
            rstdb.getInt(1)+"~"+ rstdb.getInt(2)+"~"+sum;
    }

The variable sum should contain the sum up value.

Upvotes: 1

Views: 56

Answers (2)

afzalex
afzalex

Reputation: 8652

Use map for this. You can have a map which should be mapping the specific number with sum of it's corresponding value.

int c1, c2;
Map<Integer, Integer> sum = new HashMap<>();
while (rstdb.next()) {
    c1 = rstdb.getInt(1); 
    c2 = rstdb.getInt(2);
    if(sum.containsKey(c1)) {
        sum.put(c1, sum.get(c1) + c2);
       //               ^ will return current sum of second column
    } else {
        sum.put(c1, c2);
    }
    rstdb.getInt(1)+"~"+ rstdb.getInt(2)+"~"+sum.get(c1);
}

Upvotes: 1

Bon
Bon

Reputation: 3103

You can use an integer to integer map:

Map<Integer, Integer> integerMap = new HashMap<>();

    while (rstdb.next()) {
        int column1 = rstdb.getInt(1);
        int column2 = rstdb.getInt(2);
        if (integerMap.containsKey(column1)) {
            int currentSum = integerMap.get(column1);
            integerMap.put(column1, currentSum + column2);
        } else {
            integerMap.put(column1, column2);
        }
    }

Edit: to print out the map, you can use loop through the entrySet of the map:

for (Map.Entry entry : integerMap.entrySet()) {
        System.out.println(entry.getKey() +  " : " + entry.getValue());
    }

Upvotes: 1

Related Questions