![](/img/trans.png)
[英]Efficient way of mapping keys of first map to values of second map, where value of first maps are keys of second map
[英]Efficient way to get all map values whose keys match a criterion
我在可索引的數據結構中有以下映射Map<IndexDerivedKey, Collection<Data<D>>> indexedData
。
IndexDerivedKey
符合Index
,索引由鍵和相應的值組成。 鍵用於從可索引數據結構中的元素中提取值。
例如,有一個索引,它由鍵firstName
和lastName
,我們使用此索引從具有這些屬性的對象中提取值,此操作IndexDerivedKey
每個對象產生IndexDerivedKey
。
該IndexDerivedKey
包含從上述鍵到它們各自值的映射,並用於將對象存儲在映射indexedData
,我之前已經提到過。 映射值是集合類型,因為幾個對象可能相等(相對於索引)。
問題如何提取firstName = "John"
所有對象,從而忽略lastName
的值。 顯然,我可以遍歷所有鍵並檢查O(n)
中firstName
的值。
但由於IndexDerivedKey
{firstName = "John"}
是與所有其他鍵的子集firstName = "John"
,例如{firstName = "John", lastName = "Smith"}
我想必須有一個更有效的方法。 也許利用TreeSet
?
1
public IndexDerivedKeyImpl(Index index, Map<String, String> keyValues)
{
this.keyValues = keyValues;
this.index = index;
for (String key : keyValues.keySet())
if (!index.supportsKey(key))
throw new IndexKeyMismatchException(key, index);
}
2
// in data.Index.index(Indexable)
@Override
public IndexDerivedKey index(Indexable data)
{
Map<String, String> keyValues = new HashMap<String, String>();
IndexDerivedKey key = new IndexDerivedKeyImpl(this, keyValues);
for (String k : keys)
{
String value = data.get(k);
if (value != null)
keyValues.put(k, value);
}
return key;
}
如果您想使用其他鍵訪問Map
,最好使用其他Map
:
Map<String, Collection<Data<D>>> dataByFirstName = // ...
鍵是名字。
如果搜索始終按特定順序進行,則使鍵類具有Comparable並等於。
然后使用SortedMap
,例如TreeMap
。 這也是可導航的 。 例如,您可能使用subMap(fromKey,toKey)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.