create the HashMap based on JTable

2019-09-21 15:38发布

问题:

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);

}

回答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());
}


回答2:

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());
}