2

I have below data structure like this

Country,StateID1 where StateID1 contains "City1","City2","City3" etc
Country,StateID2 where StateID2 contains "City1","City2","City3" etc

I know i can't use HashMap to implement above data structure because if i add StateID2 to same Country StateID1 will be replace with StateID2 for eg

map.put("1","1111");
map.put("1","2222");
output

 key:value
 1:2222`

i am facing hard time to figure out how to do this. I need some support from you guys

6 Answers 6

1

You need some wrapping object for storing your 'state' data. Then you can have a structure like this: Map<String, List<StateBean>>. This way you can handle a list of state for every country. If data are just Strings use Map<String, List<String>>

Sign up to request clarification or add additional context in comments.

Comments

1

You can have a Map<String, Set<String>>.

Comments

1

Store the StationIDs in an ArrayList object and add those object in a HashMap using key-value pair .. where key is the Country against the StationId ArrayList Object.

StateID1 = ["City1","City2"]    // ArrayList
StateID2 = ["City1","City2"]

Comments

1

We could have the map as Country,ListOfStates

ListOfStates could be a list that contains StateIds

Or StateIds as a Map with StateId as key and list of cities as value

Comments

0

You could create a class for the same.

class YourClass
{
     String country;
     State state;
}

class State
{
    Set<String> cities;
}

You can then use this class as a data structure. You don't really need to use Collections framework for the same.

OR

If you really want to do it using Collections, then you can use a combination of Country and StateId as the key, and the list of cities as the value in a Map. For ex:

String country = "1";
String state = "1";
String separator = "-" // You could use any separator
String key = country + separator + state;
Set<String> cities = new HashSet<String>();
cities.add("1");
cities.add("2");

Map<String, Set<String>> map = new HashMap<>(); 
map.put(key, cities);

So your key would be 1-1 and value would be 12.

Comments

0

Use can Data Structure map < String,vector < String >> , map < class T,vector < class U > >

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.