Reputation: 101
I want to query sql statement and create a hashmap to store 2 values. One being id and other the name. Then I want to add it to an ArrayList. There's something wrong with my code and it doesn't match the specific types. I don't understand what's wrong with it. Could you please explain what I'm doing wrong here? As far as I'm aware you can't add a hashmap of type <String, String>
to ArrayList but how can I achieve it in other way?
ArrayList<String> KEYWORDS = new ArrayList<String>();
String sql = "SELECT da_tag_name, da_tag_id FROM da_tags WHERE da_tag_type_id = 8";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
HashMap<String, String> row = new HashMap<String, String>();
row.put(resultSet.getString(1).toString(), resultSet.getString(2).toString());
KEYWORDS.add(row);
}
Upvotes: 0
Views: 1002
Reputation: 86
The best thing you can do is to create a custom class that represent your database Keyword object. For example:
class Keyword {
private final long id;
private final String name;
public Keyword(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return this.id;
}
public String getName() {
return this.name;
}
}
Also it is better to use the interface List instead of ArrayList. And then it goes like that:
List<Keyword> keywords = new ArrayList<>();
Then in the while loop you can add all the keywords from the ResultSet
while (resultSet.next()) {
Keyword keyword = new Keyword(resultSet.getLong(2), resultSet.getString(1));
keywords.add(keyword);
}
Upvotes: 1
Reputation: 7141
There are a few problems with this code.
Something like this:
// Note: as of Java 7 you can simplify generics using the diamond operator
List<Map<String, String>> keywords= new ArrayList<>();
String sql = "SELECT da_tag_name, da_tag_id FROM da_tags WHERE da_tag_type_id = 8";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
Map<String, String> row = new HashMap<>();
row.put(resultSet.getString(1).toString(), resultSet.getString(2).toString());
keywords.add(row);
}
Finally I would consider the design and question the use of a HashMap that only ever has one entry.
Upvotes: 3
Reputation: 31397
You need to change
ArrayList<String> keyword = new ArrayList<String>();
to
ArrayList<HashMap<String, String>> keyword = new ArrayList<>();
Because, you are trying to add row
, which is type of HashMap
to List
.
keyword.add(row);
Upvotes: 1