如何使用集合框架在 java 中实现以下数据结构
how to implement below data structure in java using collection framework
我有下面这样的数据结构
Country,StateID1 where StateID1 contains "City1","City2","City3" etc
Country,StateID2 where StateID2 contains "City1","City2","City3" etc
我知道我不能使用 HashMap 来实现上面的数据结构,因为如果我将 StateID2 添加到同一个国家,StateID1 将被 StateID2 替换
例如
map.put("1","1111");
map.put("1","2222");
output
key:value
1:2222`
我很难弄清楚如何做到这一点。我需要你们的支持
您需要一些包装对象来存储您的 'state' 数据。那么你可以有这样的结构:Map<String, List<StateBean>>
。这样您就可以处理每个国家/地区的州列表。
如果数据只是字符串,请使用 Map<String, List<String>>
You can have a Map<String, Set<String>>.
将 StationIDs
存储在 ArrayList
对象中,并使用键值对将这些对象添加到 HashMap
中。其中键是针对 StationId 的国家/地区 ArrayList
对象。
StateID1 = ["City1","City2"] // ArrayList
StateID2 = ["City1","City2"]
我们可以将地图设为 Country,ListOfStates
ListOfStates 可能是包含 StateIds
的列表
或者将 StateIds 作为以 StateId 为键并以城市列表为值的地图
可以使用数据结构 map < String,vector < String >> , map < class T,vector < class U >>
您可以为它创建一个 class
。
class YourClass
{
String country;
State state;
}
class State
{
Set<String> cities;
}
然后您可以将此 class
用作数据结构。你真的不需要为此使用集合框架。
或
如果你真的想用集合来做,那么你可以使用 Country
和 StateId
的组合作为 key
,城市列表作为 value
在 Map
中。例如:
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);
所以您的 key
将是 1-1
,值将是 12
。
我有下面这样的数据结构
Country,StateID1 where StateID1 contains "City1","City2","City3" etc
Country,StateID2 where StateID2 contains "City1","City2","City3" etc
我知道我不能使用 HashMap 来实现上面的数据结构,因为如果我将 StateID2 添加到同一个国家,StateID1 将被 StateID2 替换 例如
map.put("1","1111");
map.put("1","2222");
output
key:value
1:2222`
我很难弄清楚如何做到这一点。我需要你们的支持
您需要一些包装对象来存储您的 'state' 数据。那么你可以有这样的结构:Map<String, List<StateBean>>
。这样您就可以处理每个国家/地区的州列表。
如果数据只是字符串,请使用 Map<String, List<String>>
You can have a Map<String, Set<String>>.
将 StationIDs
存储在 ArrayList
对象中,并使用键值对将这些对象添加到 HashMap
中。其中键是针对 StationId 的国家/地区 ArrayList
对象。
StateID1 = ["City1","City2"] // ArrayList
StateID2 = ["City1","City2"]
我们可以将地图设为 Country,ListOfStates
ListOfStates 可能是包含 StateIds
的列表或者将 StateIds 作为以 StateId 为键并以城市列表为值的地图
可以使用数据结构 map < String,vector < String >> , map < class T,vector < class U >>
您可以为它创建一个 class
。
class YourClass
{
String country;
State state;
}
class State
{
Set<String> cities;
}
然后您可以将此 class
用作数据结构。你真的不需要为此使用集合框架。
或
如果你真的想用集合来做,那么你可以使用 Country
和 StateId
的组合作为 key
,城市列表作为 value
在 Map
中。例如:
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);
所以您的 key
将是 1-1
,值将是 12
。