获取这些键的值相等的键列表
我需要获取键列表,其中这些键的值与 HashMap 中的键相等。 例如,我的哈希图包含以下元素。
Key Value
1 a,b
2 e,c
3 a,b
4 f
5 e,c
6 c
我们需要评估为
1,3 contains value (a,b)
2,5 contains value (e,c)
4 contains value (f)
6 contains value (c)
Thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以反转哈希:构建一个新的哈希,其中键类型是当前映射值的类型,值类型是当前映射键类型的列表。
迭代当前地图的键,并将它们推入新地图中的正确插槽。然后您将获得所需的映射。
如果当前地图中的值现在无法直接比较,则您需要找到可以直接比较的表示形式。这完全取决于数据的性质。
一种简单的方法是对列表进行排序并使用它的 toString 表示形式作为新键。仅当底层对象的
toString
表示形式对于此目的来说是合理的时,这才有效。You could invert your hash: build a new hash with the key type being the type of your current map's value, and the value type being a list of your current map's key type.
Iterate over your current map's keys, and push them to the right slot in your new map. You'll then have exactly the mapping you are asking for.
If the values in your current map aren't directly comparable right now, you'll need to find a representation that is. This depends completely on the nature of the data.
One simple approach is to sort the list and use it's
toString
representation as your new key. This only works if thetoString
representation of the underlying objects is sane for this purpose.您可以创建其他映射,其中您的键用作值,值用作键。例如,如果您的源映射定义为
Map
创建映射Map>
。整数列表将包含具有特定值的键(来自源映射)。You can create other map where your keys a used as values and values as keys. If for example your source map is defined as
Map<Integer, String>
create mapMap<String, List<Integer>>
. The list of integers will contain keys (from your source map) that have certain values.基于 Mat 的答案,如果您需要经常执行此操作,请使用 Guava 或 Apache Commons Collections 中的双向映射类之一;例如
HashBiMap
或DualHashBidiMap
或DualTreeBidiMap
。这些数据结构维护一对表示正向和反向映射的映射。或者,对于一次性计算:
Map.entries()
集合提取到数组中。(这应该是
O(NlogN)
时间并且需要O(N)
额外空间......取决于所使用的排序算法。)Building on Mat's answer, if you need to do this operation frequently, use one of the bidirectional map classes from Guava or Apache Commons Collections; e.g.
HashBiMap<K,V>
orDualHashBidiMap
orDualTreeBidiMap
. These data structures maintain a pair of maps that represent the forward and inverse mappings.Alternatively, for a once off computation:
Map.entries()
collection into an array.(This should be
O(NlogN)
in time and requireO(N)
extra space ... depending on the sort algorithm used.)最基本的方法是:
Vector
)。完成此操作后,您将得到您想要的结果。
编辑:代码:
此代码中有一个小问题:出现重复,而且最后一个重复似乎是正确的。
使用您的示例给出的输出。 (您需要进行一些格式化)。
The most basic method will be to:
HashMap
and iterate over the map checking for keys with the same value.Vector
).After doing this, you will end up with what you want.
EDIT: The Code:
There is a little problem in this code: Duplicates occur and also the last duplicate seems to be correct.
The output using your example give. (You need to do a little formatting).