-1

There is JTable with the following content

Col1  |  Col2
A     |  1
A     |  2
A     |  3
B     |  5
B     |  1
C     |  5
C     |  4
C     |  2

Based on this table, I need to create a HashMap numbers: column 1 refers to keys and column 2 refers to data.

Below I provide my code snippet. The question is: is there any quicker way to create the mentioned HashMap?

HashMap numbers = new HashMap<String, List<String>>();

for (int i=0; i<tbNumbers.getRowCount(); i++) 
{
    col1 = mdNumbers.getValueAt(i,0).toString();
    col2Array = new ArrayList<String>();

    for (int j=0; j<tbNumbers.getRowCount(); j++) 
    {
      if (mdNumbers.getValueAt(j,0).toString() == col1)
      {
        col2Array.add(mdNumbers.getValueAt(j,1).toString());
      }
    }

    numbers.put(col1, col2Array);

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217

2 Answers2

1

Yes, maybe let the HashMap do the work instead of using a nested loop.

HashMap numbers = new HashMap<String, List<String>>();
List col2Array=null;
for (int i=0; i<tbNumbers.getRowCount(); i++) 
{
    col1 = mdNumbers.getValueAt(i,0).toString();
    col2Array = numbers.get(col1);
    if(col2Array==null){
        col2Array=new ArrayList<String>();
        numbers.put(col1,col2Array);
   }
    col2Array.add(mdNumbers.getValueAt(i,1).toString());
}
Si Kelly
  • 703
  • 3
  • 9
  • If you can rely on the order of the table it may be faster to just look for a change in col1 value. – Si Kelly Jun 20 '13 at 11:30
1

If you have the same col2 values for several c0l1, you can improve a little your algorithm:

HashMap numbers = new HashMap<String, List<String>>();

for (int i=0; i<tbNumbers.getRowCount(); i++) 
{
    col1 = mdNumbers.getValueAt(i,0).toString();
    List col2Array=null;

    col2Array = numbers.get(col1);
    if (col2Array==null) {
       col2Array=new ArrayList<String>();
    }
    col2Array.add(mdNumbers.getValueAt(j,1).toString());
}
SeniorJD
  • 6,946
  • 4
  • 36
  • 53
  • In this case at each iteration i I should create a new List col2Array. Is this correct? – Klausos Klausos Jun 20 '13 at 11:32
  • You'll create new `List` object only for new `col1` values. For the repeated ones you'll use the existing `List` object. – SeniorJD Jun 20 '13 at 11:34
  • And if you can guarantee that equal col1 values will be just in succession, the algorithm could be improved a little more :) – SeniorJD Jun 20 '13 at 11:37