Home > Back-end >  How do I get all elements of Hashmap key and values outside while loop
How do I get all elements of Hashmap key and values outside while loop

Time:09-27

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?

CodePudding user response:

The values are overridden with each iteration, that's why the first println statement correctly prints out the key and value. The Map only contains the last added pair as long as by definition it doesn't allow duplicate keys.


I recommend rather using an object encapsulating the stateName and capitalCity and adding such an object into a List.

public class State {

    private final String name;
    private final String capitalCity

    // all-args constructor and getters
}
List<State> c1 = new ArrayList<>();

...

// in the while-loop
c1.add(new State(rs.getString(3), rs.getString(3)));

Also, it is possible to group the map-values into the List resulting in Map<String, List<String>>.

Map<String, List<String>> c1 = new HashMap<>();

...

// in the while-loop
c1.computeIfAbsent("StateName", k -> new ArrayList<>()).add(rs.getString(3));
c1.computeIfAbsent("CapitalCity", k -> new ArrayList<>()).add(rs.getString(3));

An alternative solution would be using a sort of MultiValueMap (from Spring framework, but feel free to search for other libraries or frameworks if they offer something similar) that is just a wrapper to the structure above: Map<String, List<String>>.


A side note: Always program against interfaces, i.e.:

Map<String, String> map = new HashMap<>();     // :)
HashMap<String, String> map = new HashMap<>(); // :(

CodePudding user response:

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);
    }
}
  • Related