How to Use BigDecimal add method to get sum of jtable cell values?

Viewed 28

I have some data in JTable. I attempted to get sum of third column cell values, which matches with first column cell values are equal. As example T10. I can get only the existing values of third column not sum . I followed several answers in SO like,

link

Help to solve this problem is highly appreciate.

public class App_UI extends javax.swing.JFrame {

public App_UI() {
    initComponents();
}

                  
private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new java.awt.GridBagLayout());

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"01", "T10", "3000", "0.25"},
            {"02", "T12", "6000", "0.75"},
            {"03", "T10", "4500", "0.50"},
            {"04", "T16", "1500", "0.30"},
            {"05", "T12", "7500", "0.85"},
            {"06", "T10", "1500", "0.13"}
        },
        new String [] {
            "Bar Mark", "Type & Size", "Length", "Weight"
        }
    ));
    jScrollPane1.setViewportView(jTable1);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.weightx = 0.1;
    gridBagConstraints.weighty = 0.1;
    gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
    getContentPane().add(jScrollPane1, gridBagConstraints);

    jButton1.setText("Print");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
    getContentPane().add(jButton1, gridBagConstraints);

    pack();
}                 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    DefaultTableModel model1 = (DefaultTableModel) jTable1.getModel();

    for (int i = 0; i < model1.getRowCount(); i++) {

        String mark = (String) model1.getValueAt(i, 1);

        if (mark.equals("T10")) {

            BigDecimal weights = new BigDecimal((String) model1.getValueAt(i, 3));

            List<BigDecimal> listWeight = Arrays.asList(weights);

            BigDecimal tWeight = listWeight.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

            System.out.println(tWeight);

        }

    }

}                                        

public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new App_UI().setVisible(true);
        }
    });
}

              
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
}

My output is like below enter image description here

2 Answers

First, you have declared variable tWeights inside the if-block, that is it's lifetime is limited to this block, you'll get a fresh tWeights in every iteration when mark equals "T10".

Second, you use streams the wrong way and in this situation there's no advantage of using streams. Just sum it up iteratively:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    DefaultTableModel model1 = (DefaultTableModel) jTable1.getModel();
    BigDecimal tWeight = BigDecimal.ZERO; // let's start with 0 total weight

    for (int i = 0; i < model1.getRowCount(); i++) {
        String mark = (String) model1.getValueAt(i, 1);
        if (mark.equals("T10")) {
            BigDecimal weights = new BigDecimal((String) model1.getValueAt(i, 3));
            tWeight = tWeight.add(weights); // add weight to tWeight and assign the result to tWeight
            System.out.println(tWeight);
        }
    }
}                                        

Just another take on it. Maintains the listWeight as well:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel model1 = (DefaultTableModel) jTable1.getModel();
    BigDecimal weights;
    BigDecimal tWeight = new BigDecimal("0.0");
    List<BigDecimal> listWeight = new ArrayList<>(); 
    for (int i = 0; i < model1.getRowCount(); i++) {
        String mark = model1.getValueAt(i, 1).toString();
        if (mark.equals("T10")) {
            weights = new BigDecimal(model1.getValueAt(i, 3).toString());
            listWeight.add(weights);
            tWeight = tWeight.add(weights);
            // System.out.println("Growing Sum -> " + tWeight);
        }
    }
    
    // Display in Console Window...
    System.out.println("Total sum of weights based on Size 'T10':");
    StringBuilder formula = new StringBuilder("");
    for (BigDecimal bdec : listWeight) {
        if (!formula.toString().isEmpty()) {
            formula.append(" + ");
        }
        formula.append(bdec);
    }
    formula.append(" = ").append(tWeight);
    System.out.println(formula.toString());
}
Related