Daniel
Daniel

Reputation: 311

How to fill a JTable with data from a HashMap?

I'm new to Java and I want to know how to fill a JTable with HashMap data. In the hash map, the key is an integer and the value is an array of objects. I want to put the data from the hash map into the table, but I don't know how to get the values.

The HashMap:

Map<Integer, Object[]> prodList = new HashMap<>();
    
prodList.put(1, new Object[]{"Prod_1", 8000.0, 550}); //name, price, amount
prodList.put(2, new Object[]{"Prod_2", 2300.0, 15});
prodList.put(3, new Object[]{"Prod_3", 2700.0, 15});

I have been trying with this:

public TableModel fillTable(Map<?,?> prodList)
{
    DefaultTableModel tableModel = new DefaultTableModel(
            new Object[] {"key", "value"}, 0
    );
    
    for(Map.Entry<?,?> data : prodList.entrySet())
    {
        tableModel.addRow(new Object[] {data.getKey(), data.values()});
    }
    
    return tableModel;
}

But it just returns the key and this: [L] java.lang.Object; @ 1565e42a. I think I have to iterate over the array and put all the array values ​​into a new column, but I don't know how to do it.

Upvotes: 1

Views: 616

Answers (1)

camickr
camickr

Reputation: 324137

I think I have to iterate over the array and put all the array values ​​into a new column,

Correct. You can do this by adding all the values to a Vector and then add the Vector to the model.

    Iterator<Integer> iter = prodList.keySet().iterator();

    while (iter.hasNext())
    {
        Vector<Object> row = new Vector<>(4);

        Integer key = iter.next();
        row.addElement(key);

        //  Cell represents a row after the inserted row

        Object[] values =  (Object[])prodList.get(key);

        for (Object item: values)
        {
            row.addElement(item);
        }

        System.out.println(row);
        tableModel.addRow( row );
    }

The above code should will create a Vector with 4 items, the first will be the key and the last 3 will be the values in the Array that you added to the HashMap.

Note, I rarely iterate over a HashMap and I don't remember how to use the EntrySet, so I'm just using the old Iterator.

Figured out how to do it using the EntrySet:

    for(Map.Entry<Integer,Object[]> data : prodList.entrySet())
    {
        Vector<Object> row = new Vector<>(4);
        row.addElement(data.getKey());

        Object[] values = data.getValue();

        for (Object item: values)
        {
            row.addElement(item);
        }

        System.out.println(row);
        tableModel.addRow( row );
    }

Upvotes: 2

Related Questions