1

I have some data like this:

Map<Integer, String> foo

Now I can get the corresponding String with foo.get(1)

But is it also possible to get all the Integers which have the String "abc"?

Like this pseudo code: Integer[] someMore = foo.getKeys("abc")

4

4 回答 4

3

尝试:

Set<Integer> myInts = new HashSet<Integer>();
for(Entry<Integer, String> entry : foo.entrySet()) { // go through the entries
    if(entry.getValue().equals("abc")) {             // check the value
        myInts.add(entry.getKey());                  // add the key
    }
}
// myInts now contains all the keys for which the value equals "abc"
于 2013-05-24T11:59:39.443 回答
1

Map不提供按值查找。我们需要通过迭代Map条目来做到这一点

Set<Integer> matchingKeys =  new HashSet<Integer>();
for(Entry<Integer, String> e : map.entrySet()) {
    if(e.getValue().equals("abc")) {
          matchingKeys.add(e.getKey());
    }
}
于 2013-05-24T12:00:15.823 回答
0

普通地图是无法做到的。您必须自己调用foo.entrySet()和创建数组。

也许您会对使用双向地图感兴趣。这是一个线程,您可以在其中阅读一些相关信息。 Java中的双向地图?

于 2013-05-24T12:02:47.507 回答
0
Map<Integer, String> map = new Map<Integer, String>();
ArrayList<Integer> arraylist = new ArrayList<Integer>();
for (Entry<Integer, String> entry : map.entrySet()) {
    if (entry.getValue().equals("abc")) {
    arraylist.add(entry.getKey());
    }
}
于 2013-05-24T12:04:06.300 回答