rgksugan rgksugan - 1 year ago 100
Java Question

How to sort data in a table data structure in Java?

I need to sort data based on the third column of the table data structure. I tried based on the answers for the following question. But my sorting does not work. Please help me in this.
Here goes my code.

Object[] data = new Object[y];
while (rst.next()) {
int p_id = Integer.parseInt(rst.getString(1));
String sw2 = "select sum(quantity) from tbl_order_detail where product_id=" + p_id;
rst1 = stmt1.executeQuery(sw2);
String sw3 = "select max(order_date) from tbl_order where tbl_order.`Order_ID` in (select tbl_order_detail.`Order_ID` from tbl_order_detail where product_id=" + p_id + ")";
rst2 = stmt2.executeQuery(sw3);
data[i] = new Object[]{new String(rst.getString(2)), new String(rst.getString(3)), new Integer(rst1.getString(1)), new String(rst2.getString(1))};
ColumnComparator cc = new ColumnComparator(2);
Arrays.sort(data, cc);
if (i == 0) {
} else {
for (int j = 0; j < y; j++) {
Object[] theRow = (Object[]) data[j];
table.addCell((String) theRow[0]);
table.addCell((String) theRow[1]);
table.addCell((String) theRow[2]);
table.addCell((String) theRow[3]);

Sample Expected Output:

Product_code Product_name Quantity Order_date
FK Cake 3000 2010-12-09
CK Jelly 100 2010-09-23
F juice 30 2010-12-09

but what I get is:

Product_code Product_name Quantity Order_date
CK Jelly 100 2010-09-23
F juice 30 2010-12-09
FK Cake 3000 2010-12-09

Answer Source

You have far too much going on here. You're mingling database access and UI all into a single method. I'd separate those concerns.

I'd also recommend having the database do the sorting. Add an ORDER BY to the SELECT and let the database do the work.

I'd map the data from the SELECT into an object that had a Comparator for sorting. Load the ResultSet into a List of that object; you can have all your wishes that way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download