Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add objects of class to hashMap based on their values?

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.

like image 746
Eme Emertana Avatar asked Dec 09 '22 20:12

Eme Emertana


1 Answers

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);
  }
like image 102
user1406062 Avatar answered Jan 26 '23 00:01

user1406062