whiteLT
whiteLT

Reputation: 338

Storing data to hashmap

I am a little bit overwhelmed and need your advice.

I am getting some strings from database using JSON and storing them to hashmap, I can't figure out the way to store Parent and child correctly.

// looping through All JSON array
                for (int i = 0; i < data.length(); i++) {
                    JSONObject c = data.getJSONObject(i);

                    // Storing each json item in variable

                    String city = c.getString(TAG_CITY);
                    String street = c.getString(TAG_STREET);



                        HashMap<String, List<String>> ExpListData = new HashMap<String, List<String>>();
                        ExpListData.put(key, value)



                }

I can't figure out the way to store all street address to different cities. I know that I can create a List<String> for every streets in one city, but this is not an option, because database could have city, that I am not aware of

Upvotes: 1

Views: 5693

Answers (1)

AlexS
AlexS

Reputation: 5345

Your ExpListDatais discarded on every for-loop. If you want a map with city as key and all streets of that city as value use something like this:

// looping through All JSON array
HashMap<String, List<String>> ExpListData = new HashMap<String, List<String>>();
for (int i = 0; i < data.length(); i++) {
     JSONObject c = data.getJSONObject(i);

     // Storing each json item in variable
     String city = c.getString(TAG_CITY);
     String street = c.getString(TAG_STREET);

     List<String> streets = ExpListData.get(key);
     if (streets == null) {
         streets = new ArrayList<String>();
         ExpListData.put(key, streets);
     }
     streets.add(value);
 }

ExpListData will contain a map with each city as key. The value will be a list of all streets associated with that city.

The line List<String> streets = ExpListData.get(key); gets the already entered streets for the actual city. This is neccessary because otherwise the value for the key would be overriden everytime and not combined with preexisting values.

If there is the possibility, that you get a street 2 times for one city you can use a HashSet<String> instead of ArrayList<String>. Also normalizing the city-name (i.e. toLowerCase().trim() may be neccessary to get the desired result (depending on your data). Please keep in mind, that the cityname is not unique (i.e. I think in America there is more than one Springfield). So maybe using a combination of city and zipcode would be best.

Upvotes: 1

Related Questions