Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Jtable find duplicates by two columns  RSS feed

 
Karolina Kiz
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to remove duplicates from table. I want to remove only those rows which are both id and data equal. My code failed at fourth line.

int i=jTable1.getSelectedRow();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
jXDatePicker1.setFormats(dateFormat);
String date = dateFormat.format(jXDatePicker1.getDate()).toString();
String c1=jTable1.getValueAt(i, 0).toString();
String c2=jTable1.getValueAt(i, 1).toString();
String c3=jTable1.getValueAt(i, 2).toString();
String c4=jTable1.getValueAt(i, 3).toString();
String c5=price.getText().toString();
String c6=jTextField1.getText().toString();
String c7=date;
model.addRow(new Object[]{c1, c2, c3, c4, c5, c6, c7});
jTable2.setModel(model);

ArrayList<String> list = new ArrayList();
int rows = jTable2.getRowCount();
for (int m=0; m<rows; m++){
String ids = jTable2.getValueAt(m, 0).toString();
String data = jTable2.getValueAt(m, 6).toString();
if (list.contains(ids)&&list.contains(data)) {
JOptionPane.showMessageDialog(null, "Record exist");
model.removeRow(jTable2.getRowCount()-1);
}
else{
list.add(ids);
list.add(data);
}
}
image.jpg
[Thumbnail for image.jpg]
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your list does not have a coupling between the id and data. In other words, instead of checking if there is another record with the same id and data, you are checking if there is another record with the same id and another record (a possible third) with the same data.

Instead of storing the two values separately, join them in some object that properly has equals and hashCode overridden. A Map could be possible but you could also create your own little class for it. Just make sure to implement equals and hashCode, or you will never be able to easily check for existence in the List.

And whatever you do, do not use a String. Using one String to represent more than one value is bad practice.
 
Karolina Kiz
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks I fixed it .
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!