簡體   English   中英

如何使用收集框架在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`

我面臨着艱難的時間來弄清楚如何做到這一點。 我需要你們的支持

您需要一些包裝對象來存儲“狀態”數據。 然后,您可以具有如下結構: Map<String, List<StateBean>> 這樣,您可以處理每個國家/地區的州列表。 如果數據只是字符串,請使用Map<String, List<String>>

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

StationIDs存儲在ArrayList對象中,然后使用鍵值對..將其中的對象添加到HashMap ,其中key是針對StationId ArrayList對象的國家/地區。

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

我們可以將地圖設為Country,ListOfStates

ListOfStates可以是包含StateIds的列表

或將StateIds作為地圖,將StateId作為鍵並將城市列表作為值

使用can數據結構map <String,vector <String >>,map <class T,vector <class U>>

您可以為此創建一個class

class YourClass
{
     String country;
     State state;
}

class State
{
    Set<String> cities;
}

然后,您可以使用這個class的數據結構。 您實際上並不需要使用Collections框架。

要么

如果您確實想使用Collections做到這一點,則可以使用CountryStateId的組合作為key ,並使用城市列表作為Mapvalue 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM