I need to create a Integer
and String
paring, like
(1,one)
(2,two)
(3,three)
Later i want to iterate over it and get the String
for a specific Integer
value,
say like
if int val == 2
, return String.
How can i do this?
I need to create a Integer
and String
paring, like
(1,one)
(2,two)
(3,three)
Later i want to iterate over it and get the String
for a specific Integer
value,
say like
if int val == 2
, return String.
How can i do this?
Map<Integer,String> map = ...
then when you want to iterate over the keys, use
map.keySet()
to get a list of Integers used as keys
You could model this pairing association by using a 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());
}
}
Take into account that by definition of Map
, you couldn't have two different Strings for a given Integer. If you wanted to allow this, you should use a Map<Integer, List<String>>
instead.
Notice that java doesn't provide a Pair
class, but you could implement one yourself:
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
}
And then use an List<Pair<Integer,String>>
.