我做了一个如上所示的查询,得到了以下结果
mysql> SELECT DISTINCT category_id , T1 FROM 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 |
对于每个T1 couln,我试图存储category_id
使它看起来像
Popcorn=[
1,
2,
3,
4,
5,
6,
]
SoftDrinks=[
7,
8,
9,
10,
]
我遵循下面的方法来完成这个
Map<String,LinkedList<Integer>> categoryitemslist = new HashMap<String,LinkedList<Integer>>();
PreparedStatement stmt2 = connection.prepareStatement("SELECT DISTINCT category_id , T1 FROM 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);
}
谁能告诉我哪里出错了?我得到的结果是
{
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
],
}
现在你有一个单一的列表,包含所有获取的id,你把这个列表为每个T1
,而你需要为每个唯一的T1
创建一个新的列表,并将结果添加到相应的列表:
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);
}
你应该阅读这份文档。
初始化了一个空Map
Map<String,LinkedList<Integer>> categoryitemslist = new HashMap<>();
调用get()
时,如果键不存在,则返回空值
你的错误
- 您只使用了一个链表。这意味着所有键都将被映射为相同的值(在您的示例中是值列表)。我很确定这不是你的本意。
- 你没有检查一个键的值是否存在,这是避免
NPE
的一个非常重要的部分。
解决方案:
LinkedList<Integer> llist = new LinkedList<Integer>(); //remove this line
while(rs2.next()){
int category_id = (int)rs2.getInt("category_id");
String key = rs2.getString("T1");
//get value
LinkedList<Integer> llist = categoryitemslist.get(key);
//check if value exists i.e. if value isn't null, else create a new value
if(value == null){
llist = new LinkedList<Integer>();
}
//now we're sure value isn't null
llist.add(category_id);
categoryitemslist.put(key, llist);
}