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

Balázs Németh
  • 5,724
  • 7
  • 43
  • 55
gurehbgui
  • 13,218
  • 29
  • 100
  • 167
  • For that you need to create your own implementation to find keys with specific values... :) – Ketan May 24 '13 at 11:58
  • 1
    you can loop through the map and check if the value for a certain key == the String you are looking for then add it to a arrayList – benst May 24 '13 at 11:58
  • 2
    If that is the use case, then you have created the Map incorrectly, you need to swap the key and value. – Srinivas May 24 '13 at 11:59
  • Have you had a look at this: http://stackoverflow.com/questions/4005816/map-how-to-get-all-keys-associated-with-a-value ? – Balázs Németh May 24 '13 at 11:59
  • You have to iterate over the map and find all keys with a given value. This is nowhere near as efficient as the opposite though. See http://stackoverflow.com/a/46908/17713 – Matthias Meid May 24 '13 at 11:59
  • http://www.rgagnon.com/javadetails/java-0564.html might helps – Alpesh Prajapati May 24 '13 at 12:01

4 Answers4

3

Try:

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"
Jean Logeart
  • 50,693
  • 11
  • 81
  • 116
1

Map doesn't provide look-up by values. We need to do it by iterating over the Map entries

Set<Integer> matchingKeys =  new HashSet<Integer>();
for(Entry<Integer, String> e : map.entrySet()) {
    if(e.getValue().equals("abc")) {
          matchingKeys.add(e.getKey());
    }
}
sanbhat
  • 17,162
  • 6
  • 47
  • 63
0

You can't get that with a regular map. You would have to call foo.entrySet() and create the array on your own.

Maybe you would be interested in using a bidirectional map. Here's a thread where you can read a bit about that. Bi-directional Map in Java?

Community
  • 1
  • 1
Simon
  • 6,093
  • 2
  • 27
  • 34
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());
    }
}