java - Unable to store Database results into a Map -
i have made query shown above fetched me folowing results
mysql> select distinct category_id , t1 ca +-------------+--------------------+ | category_id | t1 | +-------------+--------------------+ | 1 | popcorn | | 2 | popcorn | | 3 | popcorn | | 4 | popcorn | | 5 | popcorn | | 6 | popcorn | | 7 | soft drinks | | 8 | soft drinks | | 9 | soft drinks | | 10 | soft drinks |
for each t1 coulmn , trying store category_id
so looks
popcorn=[ 1, 2, 3, 4, 5, 6, ] softdrinks=[ 7, 8, 9, 10, ]
i have followed below approach accomplish
map<string,linkedlist<integer>> categoryitemslist = new hashmap<string,linkedlist<integer>>(); preparedstatement stmt2 = connection.preparestatement("select distinct category_id , t1 categories ;"); resultset rs2 = stmt2.executequery(); linkedlist<integer> llist = new linkedlist<integer>(); while(rs2.next()) { int category_id = (int)rs2.getint("category_id"); llist.add(category_id); categoryitemslist.put(rs2.getstring("t1"), llist); }
could please let me know whats mistake ??
the result obtained
{ popcorn=[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50 ], softdrinks=[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50 ], }
right have single list contains fetched ids, , you're putting list every t1
, while need create new list every unique t1
, add results corresponding list:
while (rs2.next()) { int cid = rs2.getint("category_id"); string t1 = rs2.getstring("t1"); if (!categoryitemslist.containskey(t1)) { categoryitemslist.put(t1, new linkedlist<integer>()); } categoryitemslist.get(t1).add(cid); }
Comments
Post a Comment