返回值反转的java集合

是否有一个按以下方式工作的集合:


//什么时候


value1 -> value2 

value3 -> value4

//以便


value2 is the opposite of value1

and

value4 is the opposite of value3

//那么请求应该如下工作:


request in:value1 return out:value2

request in:value2 return out:value1

ETC


我想我可以用函数来做到这一点,但想知道是否有专门的集合。


扬帆大鱼
浏览 96回答 1
1回答

慕的地6264312

您似乎正在寻找可逆映射。已经对此进行了详细讨论:Java invert map。先前讨论的链接之一是 Apache 解决方案:https&nbsp;://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/BidiMap.html 。虽然 java 没有有效处理此问题的集合类型,但您可以通过将两个映射放在一起来自己制作一个:public class BiDiMap<T1, T2> {&nbsp; &nbsp; private final Map<T1, T2> forwardMap = new HashMap<T1, T2>();&nbsp; &nbsp; private final Map<T2, T1> reverseMap = new HashMap<T2, T1>();&nbsp; &nbsp; public void put(T1 t1, T2 t2) {&nbsp; &nbsp; &nbsp; &nbsp; T2 oldT2 = forwardMap.put(t1, t2);&nbsp; &nbsp; &nbsp; &nbsp; T1 oldT1 = reverseMap.put(t2, t1);&nbsp; &nbsp; }&nbsp; &nbsp; public void remove(T1 t1, T2 t2) {&nbsp; &nbsp; &nbsp; &nbsp; T2 currentT2 = forwardMap.get(t1);&nbsp; &nbsp; &nbsp; &nbsp; if ( currentT2 != t2 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // This is an error.&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; T1 currentT1 = reverseMap.get(t2);&nbsp; &nbsp; &nbsp; &nbsp; if ( currentT1 != t1 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Also an error.&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; forwardMap.remove(t1);&nbsp; &nbsp; &nbsp; &nbsp; reverseMap.remove(t2);&nbsp; &nbsp; }&nbsp; &nbsp; public T2 getForward(T1 t1) {&nbsp; &nbsp; &nbsp; &nbsp; return forwardMap.get(t1);&nbsp; &nbsp; }&nbsp; &nbsp; public T1 getReverse(T2 t2) {&nbsp; &nbsp; &nbsp; &nbsp; return reverseMap.get(t2);&nbsp; &nbsp; }}等等。这假设映射是一对一的。如果映射是一对多、多对一或多对多,则实现是不同的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java