Java:多对一双向查找

Ada*_*m_G 5 java dictionary hashmap

我有多对一关系的数据.我希望能够从两个方向查找数据.一个例子:

0 : a
1 : b
2 : b
3 : b
4 : c

get(0) --> a
get(1) --> b
get(a) --> 0
get(b) --> (1:3)
Run Code Online (Sandbox Code Playgroud)

这有意义吗?可能吗?

Nay*_*uki 4

这绝对是可能的。这是添加项目的代码片段:

Map<Integer,String> forwardMap = new HashMap<>();
Map<String,Set<Integer>> reverseMap = new HashMap<>();

void add(Integer x, String y) {
    forwardMap.put(x, y);
    if (!reverseMap.containsKey(y))
        reverseMap.put(y, new HashSet<Integer>());
    reverseMap.get(y).add(x);
}
Run Code Online (Sandbox Code Playgroud)

脚注:Apache Commons 有 BidiMap,Google Guava 有 BiMap,但这些似乎是一对一的映射,不允许问题中提出的多对一的情况。