Search code examples
javaswingjtablehashmaptablemodel

create the HashMap based on JTable


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

}

Solution

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