I am retrieving number of values from database, that need to be added to a list and then to a MAP with specific Key based on their values, for example,
row 1 name = "A" category = "1"
row 2 name = "B" category = "2"
row 3 name = "C" category = "1"
row 4 name = "D" category = "3"
I need to put row1 and row 3 in a list and each of row2 and row 4 in a separate list, then put these three lists into MAP and use the category names (1,2,3) as keys of MAP.
MAP
1 LIST1 (values of 2 rows)
2 LIST2 (values of 1 row)
3 LIST3 (values of 1 row)
I am not sure how to add them to the list and MAP. My constraint is that not everytime that I retrieve the values the same rows will be retrieved, so everytime I may need different number of lists to keep the values of each category that has been retrieved.
My code is as following,
ResultSet rs = st.executeQuery(SelectRows);
Map map = new HashMap();
if(rs.next())
{
item.setRowID(rs.getString("ID"));
item.setName(rs.getString("Name"));
item.setValue(rs.getString("Value"));
item.setCat(rs.getString("Cat"));
if(!map.containsKey(rs.getString("Cat"))){
map.put(rs.getString("CatID"), new ArrayList());
}
map.get(rs.getString("CatID")).add(row);
}
the last line runs into this error > "" the method add(Rows) is undefined for the type Object. even if I add the object to a list I run into the same error, the method add(List) is undefined for the type Object.
You need to create a map of lists. As you read the records, if there exist a key (here is category) then add the current row to the list
Map map = new HashMap()
for( Row row : resultset ) {
if(!map.containsKey(row.category)){
map.put(row.category, new ArrayList());
}
map.get(row.category).add(row.name);
}
UPDATE
the problem is that you need to specify generic type here
Map<String, List<Rows>> map = new HashMap<String, List<Rows>>()
while( rs.next() ) {
Rows row = new Rows();
/*
* code to initialize the values of row from the record
*/
String category = rs.getString("Cat");
if(!map.containsKey(category)){
map.put(category, new ArrayList<Rows>());
}
map.get(category).add(row);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With