0

How to get the key from Trove TIntObjectHashMap for a value that exists and been found in the map ??

if(map.containsValue(source)) {
        for (Entry<Integer, String> entry : map.entrySet()) { // entrySet() is not recognized by Trove? and i can not find any corresponding method ??
            if (entry.getValue().equals(source)) {
                entry.getKey();
        }
    }
}
Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
Maciej Cygan
  • 5,351
  • 5
  • 38
  • 72

2 Answers2

1

I would do something like this:

TIntObjectMap<String> map = new TIntObjectHashMap<>();
map.put( 1, "a" );
map.put( 2, "b" );

AtomicInteger found = new AtomicInteger( -1 );
map.forEachEntry( new TIntObjectProcedure<String>() {
    @Override
    public boolean execute( int key, String value ) {
        if ( value.equals( "a" ) ) {
            found.set( key );
            return false;
        }
        return true;
    }
} );
System.out.println( "Found: " + found.get() );

Things to remember:

  1. Obviously there could be multiple keys with the same value.
  2. The forEach* methods are the most efficient way to traverse Trove collections.
  3. You can reuse the procedures, if object allocations are a performance issue for you.
  4. If "-1" (or whatever else) is a valid key for the map, you could use another AtomicBoolean to indicate whether or not you found the value.
Rob Eden
  • 362
  • 2
  • 7
0

You can try in this way

TIntObjectHashMap<String> map = new TIntObjectHashMap<>();
map.put(1, "a");
map.put(2, "b");
//convert   TIntObjectHashMap to java.util.Map<Integer,String>
Map<Integer, String> utilMap = new HashMap<>();
for (int i : map.keys()) {
    utilMap.put(i, map.get(i));
}
Integer key=null;
if (map.containsValue("a")) {
    for (Map.Entry<Integer, String> entry : utilMap.entrySet()) { // issue solved
         if (entry.getValue().equals("a")) {
            key=entry.getKey();
           }
      }
}
System.out.println(key);

Out put:

1
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • Although this will work, there is slight implication: As per Trove "using Map.entrySet on a Trove Map is supported, but not encouraged. The reason is that this API requires the creation of the Map.Entry objects that all other parts of Trove manage to avoid.". Do you know any alternative that would use Trove native methods ? – Maciej Cygan Sep 30 '14 at 12:10
  • @MaciejCygan no. I don't know a way with `Trove` – Ruchira Gayan Ranaweera Sep 30 '14 at 12:12