2011-11-25 51 views
1

在java中,如果我有兩個對象A和B,都包含引用ID的類變量,並且A也有類變量類型,則B有一個類變量位置。我正在嘗試使用鍵作爲類型和值作爲位置來構造一個映射。目前我通過構建兩個單獨的地圖來完成這個工作,一個地圖(Map1)將引用ID鏈接到類型,並通過遍歷類型A的對象列表構建,另一個地圖(Map2)將引用ID鏈接到位置並構建通過迭代類型爲B的對象列表。然後通過遍歷Map1的keySet並找到引用id的值,將其作爲關鍵字放入新地圖,然後獲取位置值從Map2開始,並將其用作該類型的值。實現如下所示。我的問題是:有沒有更有效的方法來做這個算法?這似乎不是最好的實現。對不明的地方 - 希望代碼使問題更清楚。兩個hashmaps的普通合併

Map<String, String> referenceIdToType = new HashMap<String, String>(); 
Map<String, String> referenceIdToLocation = new HashMap<String, String>(); 

for(Info info : infoList) { 
    referenceIdToType.put(info.getReferenceId(), info.getType()); 
} 
for(Location loc : locationList) { 
    referenceIdToLocation.put(loc.getReferenceId(), loc.getLocation()); 
} 

Map<String, String> typeToLocation = new HashMap<String, String>(); 
for(String referenceId : referenceIdToType.keySet()) { 
    typeToLocation.put(referenceIdToType.get(referenceId), referenceIdToLocation.get(referenceId)); 
} 

回答

0

我的問題是:有沒有更有效的方法來做到這一點的算法?

我不認爲有一個更有效的方式來執行該操作。我甚至想不出最終的typeToLocation映射的更好的表示/實現,除非對鍵/值有特別的要求可以讓你快捷。 (順便說一句,我不會稱你正在執行「合併」的操作,從數學的角度來看,它更像是一個映射的「組合」,儘管它不是那麼嚴格,對我而言, 「合併」地圖只是建立他們的作品的結合,這就是我想你最初的意思是......)

0

爲什麼不擡頭看LocationInfo對象由referenceId,然後把它們放入一個HashMap

ArrayList<String> referenceIds = //all reference ids; 

public Location getLocationByReferenceId(String referenceId) 
{ 
    for(Location loc : locationList) 
    { 
     if(loc.getReferenceId().equals(referenceId)) 
      return loc; 
    } 
} 

public Info getInfoByReferenceId(String referenceId) 
{ 
    for(Info info : infoList) 
    { 
     if(info.getReferenceId().equals(referenceId)) 
      return info; 
    } 
} 

然後你只需要創建一個地圖,並呼籲getType()getLocation()

Map<String, String> typeToLocation = new HashMap<String, String>(); 

for(String refID : referenceIds) 
{ 
    Location loc = getLocationByReferenceId(refID); 
    Info info = getInfoByReferenceId(refID); 

    typeToLocation.put(info.getType(), loc.getLocation()); 
} 

我知道這是不是正是你要找的,但我希望它能幫助。

1

您可以通過刪除其中一個HashMaps來優化它。你只需要爲你的一個列表創建一個HashMap。然後,通過循環遍歷第二個列表來構建最終的HashMap,使用其他列表的HasMap來獲取匹配值。

Map<String, String> referenceIdToLocation = new HashMap<String, String>(); 

for(Location loc : locationList) { 
    referenceIdToLocation.put(loc.getReferenceId(), loc.getLocation()); 
} 

Map<String, String> typeToLocation = new HashMap<String, String>(); 
for(Info info : infoList) { 
    typeToLocation.put(info.getType(), referenceIdToLocation.get(info.getReferenceId())); 
}