gpt4 book ai didi

java - Java中的双向 map ?

转载 作者:IT老高 更新时间:2023-10-28 11:51:58 27 4
gpt4 key购买 nike

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

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);

有没有正确的方法来做到这两个方向?

另一个问题是我只有几个不变的值(1->"low", 2->"mid", 3->"high",所以它不值得去寻求一个复杂的解决方案。

最佳答案

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

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

关于java - Java中的双向 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10699492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com