Java中的双向地图? [英] Bi-directional Map in Java?

查看:125
本文介绍了Java中的双向地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个简单的整数到字符串映射,但是我需要能够轻松地从整数获取字符串,也可以从字符串中整数。我已经尝试过Map,但是它只能从整数中检索字符串,这是一种方式:

  private static final Map< Integer,串GT; myMap = new HashMap< Integer,String>(); 
//这样做有一个方法:
String myString = myMap.get(myInteger);

//我需要像
Integer myInteger = myMap.getKey(myString);

有没有正确的方法来做到这两个方向?另一个问题是我只有几个不变的常量值( 1->low,2-> mid,3->high,所以不值得去寻找一个复杂的解决方案。

解决方案

您可以使用Google Collections API,最近重命名为 Guava ,特别是 BiMap


一个bimap(或双向映射)是一个保存其值的
唯一性以及其键的映射,此约束
使bimaps支持反视图,这是另一个bimap
,包含与此bimap相同的条目,但带有反向键和
值。



I have a simple integer-to-string mapping in Java, but I need to be able to easily retrieve string from integer, and also integer from string. I've tried Map, but it can retrieve only string from integer, it's one way:

private static final Map<Integer, String> myMap = new HashMap<Integer, String>();
// This works one way:
String myString = myMap.get(myInteger);

// I would need something like:
Integer myInteger = myMap.getKey(myString);

Is there a right way to do it to have it both directions?

Another problem is that I only have a few constant values that don't change (1->"low", 2->"mid", 3->"high", so it wouldn't be worth to go for a complicated solution.

解决方案

You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

这篇关于Java中的双向地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆