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
  • 6,222
  • 9
  • 45
  • 60
gurehbgui
  • 14,236
  • 32
  • 106
  • 178

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
  • 52,687
  • 11
  • 83
  • 118
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,522
  • 6
  • 48
  • 64
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,293
  • 2
  • 28
  • 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());
    }
}