Issue
I have a query where I retrieve DB values like:
public HashMap<String,String> getStateCapital(String Country) {
HashMap<String,String> c1 = new HashMap<String,String>();
String query = DB query+Country;
try {
Connection db = DriverManager.getConnection(URL,Username,Password);
Statement st = db.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
c1.put("StateName",rs.getString(3));
c1.put("CapitalCity",rs.getString(4));
System.out.println(c1); // First c1 output
}
System.out.println(c1); // Second c1 output
}
}
Here when I print the first c1
I get HashMap<key,value>
Output as
{StateName=Karnata, CapitalCity=Bengaluru}
{StateName=Kerala, CapitalCity=Thiruvananthapuram}
{StateName=Telangana, CapitalCity=Hyderabad}
{StateName=TamilNadu, CapitalCity=Chennai}
etc...
But when I print the second c1
I get HashMap<key,value>
Output as
{StateName=Karnata, CapitalCity=Bengaluru}
How do I retrieve all the HashMap<key,value>
like the first c1
Output outside while loop?
Solution
Consider that Map
is a list of entries. Each entry is composed by a key
and a value
.
The key inside is unique, then the value is overridden every time you put the same key.
You can resolve to create a class that represents the state.
public class State {
private String stateName;
private String capitalCity;
public State(String stateName, String capitalCity) {
this.stateName = stateName;
this.capitalCity = capitalCity;
}
public String getStateName() {
return stateName;
}
public String getCapitalCity() {
return capitalCity;
}
@Override
public String toString() {
return "State{" +
"stateName='" + stateName + '\'' +
", capitalCity='" + capitalCity + '\'' +
'}';
}
}
And you can fill a list of State
in order to avoid overriding.
public HashMap<String, String> getStateCapital(String Country) {
List<State> states = new ArrayList<>();
String query = DB query + Country;
try {
Connection db = DriverManager.getConnection(URL, Username, Password);
Statement st = db.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
states.add(new State(rs.getString(3), rs.getString(3)));
}
System.out.println(states);
}
}
Answered By - frascu
Answer Checked By - Timothy Miller (JavaFixing Admin)