我需要创建一个Integer
和String
配对,比如
(1,one)
(2,two)
(3,three)
稍后我想迭代它并获取String
特定Integer
值,比如 if int val == 2
,返回字符串。
我怎样才能做到这一点?
我需要创建一个Integer
和String
配对,比如
(1,one)
(2,two)
(3,three)
稍后我想迭代它并获取String
特定Integer
值,比如 if int val == 2
,返回字符串。
我怎样才能做到这一点?
Map<Integer,String> map = ...
然后当你想遍历键时,使用
map.keySet()
获取用作键的整数列表
您可以使用以下方法对这种配对关联进行建模Map
:
Map m = new HashMap<Integer, String>();
m.put(1, "one");
m.put(2, "two");
m.put(3, "three");
// Iterate the keys in the map
for (Entry<Integer, String> entry : m.entrySet()){
if (entry.getKey().equals(Integer.valueOf(2)){
System.out.println(entry.getValue());
}
}
考虑到根据 的定义Map
,给定的整数不能有两个不同的字符串。如果你想允许这样做,你应该使用 aMap<Integer, List<String>>
代替。
请注意,java 不提供Pair
类,但您可以自己实现一个:
public class Pair<X,Y> {
X value1;
Y value2;
public X getValue1() { return value1; }
public Y getValue2() { return value2; }
public void setValue1(X x) { value1 = x; }
public void setValue2(Y y) { value2 = y; }
// implement equals(), hashCode() as needeed
}
然后使用List<Pair<Integer,String>>
.