Java中的双向地图

Java中的双向地图

本文介绍了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,最近重命名为,特别是


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

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

09-03 10:54